0.7.1 • Published 2 years ago

right-hand v0.7.1

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

 

NPM Version NPM Downloads  

Right-hand

A javascript library with useful helper functions

Installation

npm install right-hand

Table of contents

allTrue

Returns a function which return true if all predicates applied return a truthy value, otherwise returns false.

const result = allTrue( arg => arg === 'true', () => true);

result('true'); // true
result('false'); // false

Throws:

  • TypeError - if not every predicate is a function

allFalse

Returns a function which return true if all predicates applied return a falsey value, otherwise returns false.

const result = allFalse(arg => arg, () => false);
result(); // true
result('true'); // false

Throws:

  • TypeError - if not every predicate is a function

someTrue

Returns a function which return true if some predicates applied return a truthy value, otherwise returns false.

const result = someTrue((arg) => arg, () => true);

result(); // true
result(false); // true

Throws:

  • TypeError - if not every predicate is a function

someFalse

Returns a function which return true if some predicates applied return a falsey value, otherwise returns false.

const result = someFalse((arg) => arg, () => true);

result(false); // true
result(true); // false

Throws:

  • TypeError - if not every predicate is a function

isNullOrUndefined

Returns true if the value is undefined or null, otherwise false

isNullOrUndefined(null); // true
isNullOrUndefined(undefined); // true
isNullOrUndefined([]); // false

isNotNullOrNotUndefined

Returns true if the value is not undefined or not null, otherwise false

isNullOrUndefined(null); // false
isNullOrUndefined(undefined); // false
isNullOrUndefined('hello'); // true
isNullOrUndefined([]); // true

not

Takes a value and flip it's output

const result1 = not(() => true);
result1(); // false

const result2 = not((arg) => arg[0] === 'false');
result2(['false']); // true

lengthIsZero

Returns true if the length of the argument passed is zero, otherwise returns false

lengthIsZero([]); // true
lengthIsZero({}); // true
lengthIsZero(''); // true

isEmpty

Return true if arg passed is null | undefined | [] | {} | ''

isEmpty('') // true
isEmpty([]) // true
isEmpty({}) // true
isEmpty(undefined) // true
isEmpty(null) // true

isFunction

Returns true if the argument passed is @type function, otherwise returns false

isFunction(() => {}); // true
isFunction([]); // false;

isEqual

Performs a deep comparison between two values to determine if they are equivalent.

isEqual(1, 1)   // true
isEqual([{name: 'equal'}], [{name: 'equal'}])   // true
isEqual({ name: 'equal'}, {name: 'equal'})   // true

isEqual(1, 2)  // false
isEqual({ name: 'equalto'}, {name: 'equal'})  // false

includes

Returns true if search value includes in the collection otherwise false

includes('abcd', 'bc');  // true
includes('abcd', 'bcd');  // true
includes('abcd', ['ab', 'bc']);  // true
includes({name: 'hello'}, 'hello');  // true
includes(['test'], ['test', 'data']);  // false

propSatisfies

Returns true if specified prop condition is true otherwise returns false

const obj = { name: 'john', age: 90 };
propSatisfies(name => name === 'john','name',obj);   // true
propSatisfies(age[0] => age[0] === 60,['age'],obj);   // false

keyExists

Returns true if object has given keys otherwise false

keyExists({ name: 'hello'}, 'name')  // true
keyExists({ name: 'hello'}, 'age')  // false
keyExists({ name: 'hello'}, ['name'])    // true
keyExists({ name: 'hello'}, ['name', 'age'])   // false

and

Performs logical AND operation. null , undefined values will be considered as false value

const data: {hello?: string} = {hello: ''};
const result = and(
data,
data.hello === '',
true
);

console.log(result);   // true

or

Performs logical OR operation. null , undefined values will be considered as false value

const data: {hello?: string} = {hello: ''};
const result = or(
data,
data.hello === '',
true
);

console.log(result);   // true

ifElse

Wrapper for if else block. Returns true value if condition is met otherwise false value

ifElse(true, "truevalue", "falsevalue")();     // truevalue
ifElse((a) => a === 'a' ), "truevalue", "falsevalue")('a');    // truevalue
ifElse((a) => a === 'b' ), "truevalue", "falsevalue")('a');    // falsevalue

isArray

Returns true if the argument passed is type array, otherwise returns false

isArray([]); // true
isArray({}); // false
isArray(''); // false

isEmptyArray

Returns true if the argument passed is empty array, otherwise returns false

isArray([]); // true
isArray({}); // false
isArray(''); // false

range

Returns an array of given range

range(5);  // [1, 2, 3, 4, 5]
range(5, 10); // [5, 6, 7, 8, 9,]
range(5, 10, 0); // [0, 0, 0, 0, 0]

flatternArray

Returns a flatterned array

const arr = ['s', ['a', ['e']], '2', ['r', [[['tr']]]]];
flatternArray(arr); // [ 's', 'a', 'e', '2', 'r', 'tr' ]
flatternArray(arr, 1); // ['s', 'a', ['e'], '2', 'r', [['tr']]]

groupBy

Splits a list into sub-lists stored in an object, based on the result of calling a String-returning function on each element, and grouping the results according to values returned.

const byGrade = groupBy((student) => {
const score = student.score;
return score < 65 ? 'F' :
score < 70 ? 'D' :
score < 80 ? 'C' :
score < 90 ? 'B' : 'A';
});
const students = [{name: 'Abby', score: 84},
{name: 'Eddy', score: 58},
// ...
{name: 'Jack', score: 69}];
byGrade(students);
// {
//   'A': [{name: 'Dianne', score: 99}],
//   'B': [{name: 'Abby', score: 84}]
//   // ...,
//   'F': [{name: 'Eddy', score: 58}]
// }

prop

Selects a single property from a type and returns the value

prop('name')({ name: 'hello'}); // hello
prop('name')({ firstname: 'hello'}); // throws error

isObject

Returns true if the argument passed is @type object, otherwise returns false

isObject({}); // true
isObject({ name: 'hello' }); // true
isobject([]); // false

isEmptyObject

Returns true if the argument passed is empty object, otherwise false;

isEmptyObject({}); // true
isEmptyObject({ name: 'hello'}); // false

removeKey

const obj = {name: 'hello', firstname: "hahahha", last: {name: 'world'}};
removeKey(obj, ['firstname', 'name']); // { last: {name: 'world'}}

removeKeyWhere

const obj = {name: 'hello', first: "hahahha", last: {name: 'world'}};
const removeIfTrue = removeKeyWhere(() => true);
removeIfTrue(obj) // {}

const removeIfkeyMatches = removeKeyWhere((k, _) => k === 'name');
removeIfkeyMatches(obj); // { first: "hahahha", last: {name: 'world'} }

pickProps

Returns an object of specific properties and even we can pick deep properties. It supports an object with 9 level deep

const obj = { name: 'Dinesh', address: {line1: '709', line2: 'India'}};
pickProps(obj, ['name', 'line1']); // { name: 'Dinesh', line1: '709'}
pickProps(obj, ['name', 'pincode']); // throws error as 'pincode' is not available in Object given

mapObject

Return an modified object based on your predicate condition.

const result = mapObject((result, [key, value]) => {
 if(key === 'name') return result;
 return {
      ...result,
      [key]: value
  }
 }, {name: 'Dinesh', first: 'Senthil'});

console.log(result); //  { first: 'Senthil' }

fromEntries

const array = [ ['name', 'Bob'], ['city', 'chennai'] ];
fromEntries(array); // { name: 'Bob', city: 'chennai' }

toFlatPropertyMap

Returns a flatterned object

const obj = {name: 'hello', firstname: "hahahha", last: {name: 'world', last: { last: 'last'}}};

toFlatPropertyMap({object: obj}) // { name: 'hello', firstname: 'hahahha', 'last.name': 'world','last.last.last': 'last' }
toFlatPropertyMap({object: obj, keySeparator: '_', level: 1}) // { name: 'hello', firstname: 'hahahha', 'last_name': 'world','last_last': 'last' }

mergeObjects

const obj1 = { a:1, b: {b1: 2}};
const obj2 = { a:5, c: 3, b: { b2: 3}};

mergeObjects(obj1, obj2);

result: { a: 5, b: { b1: 2, b2: 3}, c: 3 }

updateObjectPropertyValue

const obj1 = { a: 1, b: { bb: 2 }, c: 3 };
const obj2 = { a: 2, 'b.bb': 3, delete: ['c']};
updateObjectPropertyValue(obj1, obj2);   // { a: 2, b: { bb: 3 } }

isString

Returns true if the argument passed is @type string, otherwise returns false

isString('hello'); // true
isString([]); // false;

isEmptyString

Returns true if the argument passed is empty string, otherwise returns false

isEmptyString(''); // true
isEmptyString('hello'); // false
isEmptyString([]); // false

removeAllWhitespaces

Returns a value without whitespaces

removeAllWhitespaces(' hello string '); // hellostring

Throws:

  • TypeError - Error if arg is not type string

removeExcessWhitespaces

Removes excess whitespaces from before, in the middle and after

removeAllWhitespaces(' hello       string '); // hello string

Throws:

  • TypeError - Error if arg is not type string

replaceParamsInString

replaceParamsInString('Hello {{language}} world', { language: 'typescript' }); // Hello typescript world
replaceParamsInString('Hello, {{name}} {{greeting}}', { name: 'Sam', greeting: 'welcome' }); // Hello, Sam Welcome

split

import { split } from 'right-hand';

split('hello', 'e');         // ['h', 'llo']
split('hello', 'e', 0);      // h

UsefulRegex

REGEX_EMAIL   // valid - test@gmail.com, test_one@test.in , invalid - test$@gmail.com, test@gmail, test@gmail.c
REGEX_UPPERCASE_ONLY   // valid - HELLO, invalid - hello, Hello, HEllo
REGEX_LOWERCASE_ONLY   // valid - hello, invalid - Hello, HELLO
REGEX_NUMBER_ONLY   // valid - 12345, invalid - 1234e, hello
REGEX_NON_SPECIAL_CHARACTERS   // valid - testHelo, testHelo233, invalid - test@hello, test$hello
REGEX_NON_DIGIT_CHARACTERS   // valid - testHelo, test@hello, test$hello, invalid - testHelo233, 12345
REGEX_WHOLENUMBER   // valid - 123445, invalid - 12344.56, test, -1234455
REGEX_DECIMAL_NUMBER   // valid - 1234.44, 222.2232, invalid - 123455, test, -12344
REGEX_WHOLE_OR_DECIMAL_NUMBER   // valid - 1234.44, 222.2232, 123445, invalid -  test, -12344
REGEX_ALPHANUMERIC_WITH_SPACE   // valid - test1 , 
REGEX_DATE_FORMAT_DDMMYYYY   // valid - 01/01/1990, 1-1-90, 1.1.1990, 01-01-90, invalid - 01:01:1990
REGEX_NEGATIVE_NUMBER   // valid - -12345, -1122.22, invalid - 12345
REGEX_URL   // valid - http://foo.com/, http://www.example.com/wpstyle, http://userid:password@example.com:8080, invalid - http://224.1.1.1, www.google.com
REGEX_TIME_HHMM_12_HOUR   // valid - 01:00, 5:01, invalid - 5:5, 13:00, :01
REGEX_TIME_HHMM_24_HOUR   // valid -  01:00, 5:01, 14:00 invalid - 5:5, :01
REGEX_TIME_HHMMSS_24_HOUR   // valid - 13:00:00, 09:59:23, 01:59:22, invalid - 1:00:59, 13:00
REGEX_MATCH_DUPLICATES_IN_STRING   // valid - hello and hello, invalid - hello dude
REGEX_COMPLEX_PASSWORD_STRENGTH   // valid - Purathi_219, invalid - ww11A, Puratch1
REGEX_MODERATE_PASSWORD_STRENGTH   // valid - Puratch1, invalid - hello
REGEX_MATCH_IPV4_ADDRESS   // valid - 169.253.255.255, 172.15.255.255, invalid - 256.0.0.0
REGEX_MATCH_IPV6_ADDRESS   // valid - 21DA:D3:0:2F3B:2AA:FF:FE28:9C5A, invalid - 1200:0000:AB00:1234:O000:2552:7777:1313, [2001:db8:0:1]:80
REGEX_MOBILE_NUMBER_INDIA   // valid - 9883443344, 919883443344, 91 8834433441, +917878525200, +91 8834433441, +91-9883443344, 022-24130000, invalid - 0919883443344, 0226-895623124
REGEX_POSTAL_CODE_INDIA   // valid - 607106, 234 543, invalid - 0122343, 12345

// Usage
import { RegExConstant } from 'right-hand';

RegExConstant.REGEX_UPPERCASE_ONLY.test('HELLO');  // true

fake

Useful to generate fake data. Inspired by faker.js. Define your object structure and generate random data for that. Support nested level object. Stictly typed, compiler error will be thrown if type is incorrect.

import { fake } from 'right-hand';

fake('first-name');     // Tess Von
fake('email');          // louie536@hotmail.com

// constructing object to fake
fake([]);               // {}
fake(['name', 'first-name']);     // { name: Tess Von }
fake([, 'first-name']);     //  Tess Von 
fake(['name', 'array-child:1', ['fullname', 'fullname']]);
// output => { name: [ { fullname: 'Dinkar Rice' } ] }
fake([, 'array-child:1', ['fullname', 'fullname']]);
// output => [ { fullname: 'Dinkar Rice' } ]
fake([
    ['name', 'fullname'],
    ['email', 'email']
]);
// output => { name: 'Atreyi Schinner', email: 'jerad405@outlook.com' }

// constructing nested object to fake
// type object-child will help us to construct nested object. 
fake(
    ['name', 'object-child', ['first-name', 'first-name'], ['last-name', 'last-name']],
    ['email', 'email']
);

// output => { name: { 'first-name': 'Porter', 'last-name': 'Hagenes' }, email: 'gati_dubashi@hotmail.com' }


 [ 'name',      'object-child',           ['first-name', 'first-name'] ]

  field name     type of value to fake     children for type object-child and array-child

// constructing nested array to fake
// type array-child works little different. it expects single child third value in array. If provided more than one child, last one will be picked.
// if child has field name, it will be considered as array of object.
// if child has no field name, then it will be considered as array of value.
// if we need to generate more than one array child, then use 'array-child:5' (array-child:{number})
fake(
    ['name', 'array-child', [, 'first-name']],
    ['email', 'email']
);
// output => { name: [ 'Waldo' ], email: '29wilfrid@outlook.com' }

fake(
    ['name', 'array-child:3', [, 'first-name']],
    ['email', 'email']
);
// output => { name: [  'Mitchell', 'Katharina', 'Oran' ], email: 'halle_adams@hotmail.com' }

fake(
    ['name', 'array-child', ['first-name', 'first-name']],
    ['email', 'email']
);
// output => { name: [ { 'first-name': 'Waldo' } ], email: '29wilfrid@outlook.com' }

Another way
fake({    
    'name.first-name': 'first-name',
    'name.last-name': 'last-name',
    'city': 'default:chennai'
});
// output => { name: { 'first-name': 'Amara', 'last-name': 'Harvey' }, city: 'chennai' }

fake({    
    'name': 'first-name',
    'address': [, 'array-child', ['name', 'fullname']]
});
// output => { name: 'Nathan', address: [ { city: 'chennai' } ] }

Types to fake

'default:${value}'          // usage => 'default:hello' => value defaults to hello
'description' 
'email' 
'image-placeholder' 
'username' 
'fullname'
'first-name' 
'last-name'
'boolean' 
'array-child'
'array-child:${number}''   // usage => 'array-child:1', 'array-child:2' to any finite number
'object-child'
'uuid'
'uuid.nil'
'digit:${number}'         // usage => 'digit:1', 'digit:2'  to any finite number
'Month Yr'              // February 2009
'Month D, Yr'           // February 17, 2009
'D Month, Yr'           // 17 February, 2009
'Yr, Month D'           // 2009, February 17
'Mon D, Yr'             // Feb 17, 2009
'D Mon, Yr'             // 17 Feb, 2009
'Yr, Mon D'             // 2009, Feb 17
'ISO'                   // 2022-03-20T13:47:50.466Z
'dateString'            // "Fri Nov 11 2016"
'DD-MMM-YYYY'           // 30-Dec-2011
'MMDDYY'                // 03112009
'DDMMYY'                // 11032009
'YYMMDD'                // 20090301
'YYYY-MM-DD HH:mm:ss'   // 2012-06-22 05:40:06
// more types coming...
0.7.1

2 years ago

0.7.0

2 years ago

0.6.0

2 years ago

0.5.0

2 years ago

0.4.0

3 years ago

0.3.0

3 years ago

0.2.0

3 years ago

0.1.0-beta

3 years ago

0.1.0

3 years ago