@pastable/utils
A collection of very short utils functions for about anything, without depenencies. Something like a (very) tiny (incomplete) nicely typed lodash.
Some are taken from other open-source projects, such as Chakra-UI
.
List of utils
Array
getDiff
: Return the difference between left in rightgetSymmetricDiff
: Return the difference between left in right / right in leftgetUnion
: Return the union between left & rightgetIntersection
: Return the intersection between left & righthasAll
: Checks that all items (right) are in left arrayuniques
: Return uniques/de-duplicated values in arrayfindBy
: Find an item/index from its value using a property path in the array (can be nested using a dot delimited syntax)sortBy
: Sort an array of objects by a common key in given direction (asc|desc, defaults to asc)isEqualArrays
: Compare arrays & return true if all members are included (order doesn't matter)combineUniqueValues
: Combine one or more array into the first one while pushing only distinct unique valuesfirst
: Get first item of arraylast
: Get last item of arrayflatMap
: Polyfill Array.flatMapmakeArrayOf
: Make an array of {count} empty elementschunk
: Split an array in chunk of given sizepluck
: Array of picked property- `prependItem`
- `appendItem`
updateItem
: Update an object item inside given array, found by passed idPathremoveValue
: Returns array without given valueremoveValueMutate
: Same asremoveValue
but mutate original array (useful for Proxy states)removeItem
: Returns array without given item objectremoveItemObjectMutate
: Same asremoveItem
but mutate original array (useful for Proxy states)- `updateAtIndex`
- `removeAtIndex`
removeAtIndexMutate
: Same asremoveAtIndex
but mutate original array (useful for Proxy states)getPrevItem
: Returns prev item from given index, handles loopinggetNextItem
: Returns next item from given index, handles loopinggetNextIndex
: Returns next index from given index, handles loopinggetPrevIndex
: Returns prev index from given index, handles loopingsortArrayOfObjectByPropFromArray
: Sort array of object by given prop using a reference order array, sort items not in reference order in lasts positions
Asserts`
- `isDefined`
isPrimitive
: Returns true if value is a string|number|booleanisObject
: Returns true if typeof value is object && not nullisObjectLiteral
: Returns true if value extends basic Object prototype and is not a Date- `isDate`
- `isPromise`
isType
: Can be used as type guard- `isClassRegex`
- `isClass`
- `isServer`
- `isBrowser`
- `isProd`
- `isDev`
- `isTest`
Getters`
getSelf
: Really, it just returns the value you passmakeSelfGetters
: Make an object where the keys will have a self getter as valuefirstKey
: Get 1st/only key of objectfirstProp
: Get 1st/only prop of objectprop
: Make getter on obj[key]
Misc`
callAll
: Returns a callback that will call all functions passed with the same argumentscompose
: Compose right-to-leftpipe
: Compose left-to-right, most commonly usedwait
: Wait for X ms till resolving promise (with optional callback)getInheritanceTree
: Gets given's entity all inherited classes. (taken fromtypeorm
)on
/off
: Shorthand to add an event listener
Nested`
set
: Sets a nested property value from a dot-delimited pathget
: Get a nested property value from a dot-delimited path.remove
: Remove key at path in an objectdeepMerge
: Deep merge arrays from left into right, can use unique array values for merged propertiesdeepSort
: Deeply sort an object's properties using given sort function
Object`
mapper
: Map an object to another using given schema, can use a dot delimited path for mapping to nested propertiesreverse
: Reverse an object from its schemamakeInstance
: Make an instance of given class auto-filled with record valuesfromEntries
: Polyfill Object.fromEntriessortObjectKeys
: Sort object keys alphabeticallysortObjKeysFromArray
: Sort object keys using an order array
Pick`
pick
: Pick given properties in objectpickBy
: Creates an object composed of the picked object properties that satisfies the condition for each valuepickDefined
: Only pick given properties that are defined in objectomit
: Omit given properties from objectformat
: Keep only truthy values & format them using a given methodremoveUndefineds
: Remove undefined properties in objecthasShallowDiff
: Returns true if a value differs between a & b, only check for the first level (shallow)getCommonKeys
: Returns keys that are both in a & bhasShallowDiffInCommonKeys
: Returns true if a value differs between a & b in their common properties
Primitives`
parseStringAsBoolean
: Parse 'true' and 1 as true, 'false' and 0 as false- `snakeToCamel`
- `kebabToCamel`
- `camelToSnake`
- `camelToKebab`
- `uncapitalize`
- `capitalize`
limit
: Limit a number between a [min,max]limitStr
: Limit a string to a lengthareRectsIntersecting
: Returnstrue
if 2 DOMRect are intersecting (= elements collision)getSum
: Get the sum of an array of numberforceInt
: Force a string to number, handleNaN
by fallbacking todefaultValue
(= 1 if not provided)getPageCount
: Returns total page count fromitemsCount
&pageSize
roundTo
: Returns a float rounded toX
decimals, defaults to 2getClosestNbIn
: Return the closest nb in array, ex:getClosestNbIn([0, 50, 100, 200], 66); // = 50
stringify
: JSON.stringify wrapped with try/catchsafeJSONParse
: JSON.parse wrapped with try/catch
Random`
getRandomString
: Return a random string of given length, can be passed a custom alphabet to pick random characters ingetRandomIntIn
: Return a random int between min/max, if only 1 arg (max) is passed then min is set to 0getRandomFloatIn
: Return a random int between min/max, if only 1 arg (max) is passed then min is set to 0, 3rd arg rounds to X decimalsgetRandomPercent
: Return a random nb between [0, 100], can be given the nb of decimals to return, defaults to 2pickMultipleUnique
: Randomly pick N unique element in array while excluding some if neededpickOne
: Returns a random element in given arraypickOneBut
: Returns a random element in given array but not of the excludedpickOneInEnum
: pickOne but for typescript enumsmakeArrayOfRandIn
: Make an array of [min, max] empty elements
Set`
Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set