stunsail · 
TIPstunsail pairs nicely with param.macro, a Babel plugin for compile-time partial application & lambda parameters
allcollectionslogic v1.0.0
all(collection, fn)
Universal version of native Array#every that works on pretty much any
iterable - Arrays & Array-likes, Objects, Sets, Maps, strings, custom
iterables, etc.
Returns true if the result of fn is truthy for every item in the
collection, or stops iteration early and returns false if some item
causes fn to return a falsy value.
fn defaults to value => !!value so that collection can quickly be
tested for truthiness throughout.
ARGUMENTS
| name | type | description |
|---|---|---|
| collection | object |
Iterable-like object to map over, applying fn on each iteration |
| fn | Function |
Callback applied to each item in collection |
RETURNS
boolean – whether all arguments satisified the condition
USAGE
all([1, 3, 5, 7], v => v < 10)// -> trueall({ one: 1, two: 2, three: 3 }, v => v === 3)// -> false
SEE ALSO
anycollectionslogic v1.0.0
any(collection, fn)
Universal version of native Array#some that works on pretty much any
iterable - arrays & array-likes, objects, Sets, Maps, strings, custom
iterables, etc.
Returns true if the result of fn is truthy for any item in the
collection, or stops iteration early and returns false if some item
causes fn to return a falsy value.
fn defaults to val => !!val so that collection can quickly be tested
for truthiness throughout.
ARGUMENTS
| name | type | description |
|---|---|---|
| collection | object |
Iterable-like object to map over, applying fn on each iteration |
| fn | Function |
Callback applied to each item in collection |
RETURNS
boolean – whether any item satisifed the condition
USAGE
any({ one: 1, two: 2, three: 3 }, v => v === 3)// -> trueany([1, 3, 5, 7], v => v > 10)// -> false
SEE ALSO
applyfunctions v1.0.0
apply(fn, args)
Call fn using the array args as its arguments. Similar to native
Function#apply() but does not set the function's this value.
ARGUMENTS
| name | type | description |
|---|---|---|
| fn | Function |
Function to which args will be applied |
| args | array |
Array of arguments to apply to fn |
RETURNS
any – result of applying args to fn
USAGE
apply(Math.max, [99, 5, 302])// -> 302const max = apply(Math.max)max([1, 2, 100, 4])// -> 100
camelCasestrings v1.0.0
camelCase(string)
Convert the given string to camelCase.
ARGUMENTS
| name | type | description |
|---|---|---|
| string | string |
Input string to convert to camel-case |
RETURNS
string
USAGE
camelCase('A space separated string')// -> 'aSpaceSeparatedString'camelCase('snake_cased_thing')// -> 'snakeCasedThing'camelCase('alreadyCamelCased')// -> 'alreadyCamelCased'
capfunctions v1.0.0
cap(fn)
Add a cap on the number of arguments passable to fn. Any arguments beyond
limit will not be passed, which is useful for creating functions
compatible with currying or as callbacks / parameters to higher order
functions.
ARGUMENTS
| name | type | description |
|---|---|---|
| fn | Function |
Function whose arguments to limit |
| limit | Number |
The number of arguments to allow (default = 1) |
RETURNS
Function – new function accepting only limit arguments
USAGE
const log = cap(console.log, 2)log(1, 2, 3)// -> [ 1, 2 ];['1', '2.2', '2.54'].map(parseInt)// -> [ 1, NaN, NaN ]const toInt = cap(parseInt);['1', '2.2', '2.54'].map(toInt)// -> [ 1, 2, 2 ]
clampnumbers v1.0.0
clamp(value, lower, upper)
Ensures that a number value is between bounds lower and upper.
If value is not a number it's assumed to be 0, while lower and
upper are set to value when they aren't numbers (or aren't provided).
ARGUMENTS
| name | type | description |
|---|---|---|
| value | number |
The number to operate on |
| lower | number |
Lower bound |
| upper | number |
Upper bound |
RETURNS
number – between lower & upper
USAGE
clamp(20, -10, 10)// -> 10clamp(-15, -10, 10)// -> -10
countcollectionsstrings v1.0.0
count(collection, search, maxOccurrences)
Return the number of occurrences of search in collection, up to
maxOccurrences if provided.
Numbers are checked for divisiblity, i.e. 4 can fit in 9 twice,
so it could be said that there are 2 occurrences of 4 in 9.
Strings are treated as collections. All other primitives are checked for equality.
ARGUMENTS
| name | type | description |
|---|---|---|
| collection | any |
Collection in which to search |
| search | any |
Value to search for |
| maxOccurrences | number |
Max occurrences to search for (optional) |
RETURNS
number – occurrences found
USAGE
count([1, 6, 6, 3], 6)// -> 2count('hello world', 'l')// -> 3count('hello world', 'l', 2)// -> 2count(new Set([1, 6, 6, 3]), 6)// -> 1count({ a: 'hello', b: 'hello' }, 'hello')// -> 2const map = new Map()map.set('a', 5)map.set('b', 5)map.set('c', 10)count(map, 5)// -> 2
defaultsobjects v1.0.0
defaults(object, extension)
Sets own properties from extension on object if any of them are not
present on object.
ARGUMENTS
| name | type | description |
|---|---|---|
| object | object |
Base object to extend |
| extension | object |
Object containing default properties |
RETURNS
object
USAGE
const base = { abc: '123', def: '456' }const ext = { abc: '999', ghi: '789' }const result = defaults(base, ext)// -> { abc: '123', def: '456', ghi: '789' }
eachcollections v1.0.0
each(collection, fn)
Universal version of native Array#forEach that works on pretty much any
iterable - arrays & array-likes, objects, Sets, Maps, strings, custom
iterables, etc.
ARGUMENTS
| name | type | description |
|---|---|---|
| collection | Iterable |
Iterable-like object to iterate over |
| fn | Function |
Called with each iteration |
RETURNS
undefined
USAGE
each([1, 2, 3], v => console.log(v))// -> 1 2 3each('string', v => console.log(v))// -> s t r i n geach({ key: 'value', keyTwo: 'valueTwo' }, v => console.log(v))// -> 'value' 'valueTwo'each(new Set([1, 2, 3]), v => console.log(v))// -> 1 2 3const map = new Map()map.set('keyOne', 'valueOne')map.set('keyTwo', 'valueTwo')each(map, v => console.log(v))// -> 'value' 'valueTwo'const obj = {* [Symbol.iterator] () {for (const n of [1, 2, 3]) {yield n}}}each(obj, v => console.log(v))// -> 1 2 3
filtercollections v1.0.0
filter(collection, fn)
Universal version of native Array#filter that works on pretty much any
iterable - arrays & array-likes, objects, Sets, Maps, strings, custom
iterables, etc.
fn is called with arguments value, key, collection. If the result
is truthy, the element will be present in the resulting collection. If the
result is falsy, it will be filtered.
ARGUMENTS
| name | type | description |
|---|---|---|
| collection | Iterable |
Iterable-like object from which to filter items |
| fn | Function |
Predicate that decides whether to remove the item |
RETURNS
any – same type as collection
USAGE
const object = { one: 1, two: 2, three: 3 }filter(object, value => value % 2)// -> { one: 1, three: 3 }const array = [1, 2, 3, 4, 5]filter(array, value => value % 2)// -> [1, 3, 5]filter('foobar', value => value !== 'o')// -> fbar
firstcollections v1.0.0
first(collection)
Retrieve the item at index zero of the given array-like or Set object.
For Sets this is based on insertion order, i.e. the first inserted object.
ARGUMENTS
| name | type | description |
|---|---|---|
| arrayLike | array |
Array-like value to access |
RETURNS
any – first value of the given collection, i.e. array[0]
USAGE
first([1, 2, 3, 4])// -> 1first(new Set([1, 2, 3, 4]))// -> 1first((function () { return arguments }(1, 2, 3, 4)))// -> 1
SEE ALSO
getobjects v1.0.0
get(object, path)
Access a property of object at path safely & deeply, returning
undefined if it doesn't exist.
ARGUMENTS
| name | type | description |
|---|---|---|
| object | object |
Object-like value to access |
| path | string | string[] |
String using dot or bracket syntax, or an array of path segments |
RETURNS
any
USAGE
const object = { attributes: { flammable: true } }get(object, 'attributes.toxic')// -> undefinedget(object, 'attributes.flammable')// -> trueconst objectTwo = { array: [1, 2, 3] }// these are equivalentget(objectTwo, 'array[2]')get(objectTwo, 'array.2')// -> 2get(objectTwo, 'array[3]')// -> undefined
getOrobjects v1.0.0
getOr(object, path, defaultValue)
Access a property of object at path safely & deeply, returning
defaultValue if it doesn't exist.
ARGUMENTS
| name | type | description |
|---|---|---|
| object | object |
Object-like value to access |
| path | string | string[] |
String using dot or bracket syntax, or an array of path segments |
| defaultValue | any |
Value to return if path resolves to nil |
RETURNS
any
USAGE
const object = { attributes: { flammable: true } }getOr(object, 'attributes.toxic', false)// -> falsegetOr(object, 'attributes.flammable', false)// -> trueconst objectTwo = { array: [1, 2, 3] }// these are equivalentgetOr(objectTwo, 'array[2]', 'item three')getOr(objectTwo, 'array.2', 'item three')// -> 2getOr(objectTwo, 'array[3]', 'item four')// -> 'item four'
getTypetypes v1.0.0
getType(value)
Alternative to the builtin typeof operator that returns a more accurate
type string.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
RETURNS
string
USAGE
getType('hi!')// -> stringgetType({})// -> objectgetType([])// -> arraygetType(null)// -> nullgetType(new RangeError())// -> rangeerror
SEE ALSO
hasobjects v1.0.0
has(object, path)
Alternative to the builtin Object#hasOwnProperty function with support
for deep-property access using both dot and bracket syntax.
ARGUMENTS
| name | type | description |
|---|---|---|
| object | object |
Object-like value to access |
| path | string | string[] |
String using dot or bracket syntax, or an array of path segments |
RETURNS
boolean
USAGE
const object = { attributes: { flammable: true } }has('attributes.flammable', object)// -> trueconst objectTwo = { array: [1, 2, 3] }// these are equivalenthas(objectTwo, 'array[2]')has(objectTwo, 'array.2')// -> truehas(objectTwo, 'array[3]')// -> false
includescollections v1.0.0
includes(value, collection)
Check whether value is included in collection. This is a version of
isOneOf() with the arguments flipped.
ARGUMENTS
| name | type | description |
|---|---|---|
| collection | object |
List to check value against |
| value | any |
Value to search for in collection |
RETURNS
boolean
USAGE
includes([1, 2, 3], 2)// -> trueincludes({ key: 'value' }, 'value')// -> true
SEE ALSO
invariantlogic v1.0.0
invariant(condition, message)
Test that condition is truthy and return its value,
or throw an error with message when it is falsy.
message defaults to 'Invariant Violation'.
ARGUMENTS
| name | type | description |
|---|---|---|
| condition | any |
Value to test |
| message | string |
Message thrown with the error when condition is falsy |
RETURNS
any
USAGE
const truthyCondition = () => {}const result1 = invariant(truthyCondition, 'No function provided.')// -> () => {}const falsyCondition = nullconst result2 = invariant(truthyCondition, 'No function provided.')// -> InvariantError: 'No function provided.'
isEqualtypeslogic v1.0.0
isEqual(a, b)
Check whether two values a and b are deeply equal. Works on almost any
object - including plain objects, arrays, Maps, Sets, and Dates.
ARGUMENTS
| name | type | description |
|---|---|---|
| a | any |
|
| b | any |
RETURNS
boolean
USAGE
isEqual({}, {})// -> trueisEqual(new Set([1, 2, 3]), new Set([1, 2, 3]))// -> trueisEqual(new Set([1, 2]), new Set([9, 10]))// -> false
isArraytypeslogic v1.0.0
isArray(value)
Check whether value is an array, like the built-in
Array.isArray() method.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isArray([1, 2, 3])// -> trueisArray({ length: 2, 0: 'foo', 1: 'bar' })// -> false
isArrayLiketypeslogic v1.0.0
isArrayLike(value)
Check whether value is an array or an object with a length
property and that it also has a property at length - 1.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isArrayLike([1, 2, 3])// -> trueisArrayLike(null)// -> falseisArrayLike('foobar')// -> trueisArrayLike({ length: 2 })// -> falseisArrayLike({ length: 2, 0: 'foo', 1: 'bar' })// -> true
isBooleantypeslogic v1.0.0
isBoolean(value)
Check whether value is a boolean.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
any
USAGE
isBoolean(true)// -> trueisBoolean(false)// -> trueisBoolean(0)// -> false
isBuffertypeslogic v1.0.0
isBuffer(value)
Check whether value is a Buffer.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isBuffer(Buffer.from('string'))// -> trueisBuffer('string')// -> false
isDatetypeslogic v1.0.0
isDate(value)
Check whether value is a Date instance.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isDate(new Date())// -> trueisDate(Date.now())// -> false
isEmptytypeslogic v1.0.0
isEmpty(value)
Check whether value is an empty version of its type, i.e. {} for objects,
[] for arrays, etc.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
// examples of `true` cases:isEmpty({})isEmpty([])isEmpty(null)isEmpty('')isEmpty(' \t \n')// examples of `false` cases:isEmpty({ property: 'hello' })isEmpty([1, 2, 3])isEmpty(() => {})isEmpty('a value')
isErrortypeslogic v1.0.0
isError(value)
Check whether value is a built-in Error type.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isError(new Error('did a bad thing'))// -> trueisError(new TypeError('wrong kind of thing'))// -> trueisError({ code: 'ENOENT', message: 'wrong' })// -> false
isFunctiontypeslogic v1.0.0
isFunction(value)
Check whether value is a function.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
// examples of `true` cases:isFunction(Function)isFunction(() => {})isFunction(async () => {})isFunction(function () {})isFunction(function * () {})// examples of `false` cases:isFunction(false)isFunction('')isFunction([])isFunction({})isFunction(new Map())isFunction(new Set())isFunction(new Date())isFunction(null)isFunction(undefined)isFunction(1)
isInRangetypeslogic v1.0.0
isInRange(value, start, end)
Check whether value is between start and end, inclusively.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | number |
Value to test |
| start | number |
Lower boundary |
| end | number |
Upper boundary |
RETURNS
boolean
USAGE
isInRange(20, 0, 40)// -> trueisInRange(-10, 0, 40)// -> falseisInRange(10, 0, 10)// -> true
SEE ALSO
isIterabletypeslogic v1.0.0
isIterable(value)
Check whether value is an iterable object, i.e. its [Symbol.iterator]
property is set as a function.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isIterable([])// -> trueisIterable({})// -> falseisIterable(new Set())// -> trueisIterable(new Map())// -> trueisIterable({ [Symbol.iterator] () {} })// -> trueisIterable(null)// -> false
isMaptypeslogic v1.0.0
isMap(value)
Check whether value is a Map object.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isMap(new Map())// -> trueisMap({})// -> false
isNantypeslogic v1.0.0
isNan(value)
Check whether value is NaN.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isNan(NaN)// -> trueisNan(40)// -> falseisNan('string')// -> falseisNan({})// -> false
isNiltypeslogic v1.0.0
isNil(value)
Check whether value is null or undefined.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isNil(null)// -> trueisNil(undefined)// -> trueisNil(false)// -> false
isNumbertypeslogic v1.0.0
isNumber(value)
Check whether value is a number.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isNumber(4)// -> trueisNumber(NaN)// -> false
isNumerictypeslogicstringsnumbers v1.0.0
isNumeric(value)
Check whether value is a number or a string that appears to be a number,
including integers & decimals in strings.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
// examples of `true` cases:isNumeric(1)isNumeric(1.343)isNumeric(Infinity)isNumeric('1')isNumeric('1.6')isNumeric('943034.3923')// examples of `false` cases:isNumeric(false)isNumeric([])isNumeric({})isNumeric(new Map())isNumeric(new Set())isNumeric(new Date())isNumeric(NaN)isNumeric(null)isNumeric(undefined)
isObjecttypeslogic v1.0.0
isObject(value)
Check whether value is a plain object.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isObject({})// -> trueisObject(() => {})// -> falseisObject(new Map())// -> false
isOneOfcollections v1.0.0
isOneOf(value, collection)
Check whether value is included in collection. This is a version of
includes() with the arguments flipped.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to search for in collection |
| collection | object |
List to check value against |
RETURNS
boolean
USAGE
isOneOf(2, [1, 2, 3])// -> trueisOneOf('value', { key: 'value' })// -> true
SEE ALSO
isPrimitivetypeslogic v1.0.0
isPrimitive(value)
Check whether value is a primitive, i.e. one of:
nullstringnumberbooleanundefined
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
// examples of `true` cases:isPrimitive(null)isPrimitive('string')isPrimitive(4)isPrimitive(true)isPrimitive(undefined)// examples of `false` cases:isPrimitive({})isPrimitive([])isPrimitive(new Date())
isSettypeslogic v1.0.0
isSet(value)
Check whether value is a Set object.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isSet(new Set())// -> trueisSet([])// -> false
isStringtypeslogic v1.0.0
isString(value)
Check whether value is a string.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isString('something here')// -> trueisString(400)// -> false
isSubsetobjectslogic v1.0.0
isSubset(superset, subset)
Check if a given object is a subset of another, recursively.
This differs from matches, which will check that
the given properties of one object are deeply equal to those same
properties in another — without the recursive partial behavior.
ARGUMENTS
| name | type | description |
|---|---|---|
| superset | object |
Object to compare with subset |
| subset | object |
Object containing properties to match |
RETURNS
boolean
USAGE
const path = {id: 100,label: "greeting",node: {kind: "string",value: "hello"}}isSubset(path, { label: "greeting" })// -> trueisSubset(path, { node: { value: "hello" } })// -> trueisSubset(path, { node: { kind: "number" } })// -> false
SEE ALSO
isThenabletypeslogic v1.0.0
isThenable(value)
Check whether value is an object with a then method.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
RETURNS
boolean
USAGE
isThenable(Promise.resolve())// -> trueisThenable({ then () {} })
isTypetypeslogic v1.0.0
isType(value, type)
If type is a string, check whether value has that type. Other kinds will
check that the types of type and value match.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to test |
| type | any |
Type string or a value whose type will be checked against that of value |
RETURNS
boolean
USAGE
isType('bar', 'string')// -> trueisType('3', 'number')// -> falseisType(new Date(), Date)// -> true
SEE ALSO
kebabCasestrings v1.0.0
kebabCase(string)
Convert the given string to kebab-case.
ARGUMENTS
| name | type | description |
|---|---|---|
| string | string |
Input string to convert to kebab-case |
RETURNS
string
USAGE
kebabCase('A space separated string')// -> 'a-space-separated-string'kebabCase('camelCasedThing')// -> 'camel-cased-thing'kebabCase('already-kebab-cased')// -> 'already-kebab-cased'
lastcollections v1.0.0
last(collection)
Retreive the item at the highest index of the given array-like or Set object.
For Sets this is based on insertion order, i.e. the last inserted object.
ARGUMENTS
| name | type | description |
|---|---|---|
| arrayLike | array |
Array-like value to access |
RETURNS
any – last value of the given collection, i.e. array[array.length - 1]
USAGE
last([1, 2, 3, 4])// -> 4last(new Set([1, 2, 3, 4]))// -> 4last((function () { return arguments }(1, 2, 3, 4)))// -> 4
SEE ALSO
matchesobjectslogic v1.0.0
matches(object, compare)
Check that all properties of compare are deeply equal to those same
properties of object.
This differs from isSubset, which will recurse into an object's properties to check whether they are subsets of those same paths in another object.
ARGUMENTS
| name | type | description |
|---|---|---|
| object | object |
Object on which to check for properties of compare |
| compare | object |
Object containing properties to match |
RETURNS
boolean
USAGE
const wishy = { name: 'wishy', color: 'green' }matches(wishy, { color: 'green' })// -> trueconst washy = { name: 'washy', color: 'red' }matches(washy, { color: 'blue' })// -> falseconst arr = [{ name: 'willy', color: 'red' },{ name: 'wally', color: 'red' },{ name: 'dopey', color: 'brown' },{ name: 'wishy', color: 'blue' },{ name: 'washy', color: 'green' }]arr.find(o => matches(o, { color: 'green' })// -> { name: 'washy', color: 'green' }arr.find(o => matches(o, { color: 'brown' })// -> { name: 'dopey', color: 'brown' }arr.find(o => matches(o, { color: 'red' })// -> { name: 'willy', color: 'red' }
SEE ALSO
oncefunctions v1.0.0
once(fn)
Return a wrapped version of fn that is only able to execute
a single time. Further calls to the wrapped function will return
the value from the original call.
ARGUMENTS
| name | type | description |
|---|---|---|
| fn | Function |
Function to wrap so that it only executes a single time |
RETURNS
Function
USAGE
function expensive (someNumber) {return someNumber}const wrapped = once(expensive)wrapped(100)// -> 100wrapped(93247593475)// -> 100
partitioncollections v1.0.0
partition(collection, fn)
Iterate over collection and apply fn to each item,
returning an array where the first element contains all items
for which fn returned a truthy value, and the second element
contains all items for which it returned a falsy value.
ARGUMENTS
| name | type | description |
|---|---|---|
| collection | object |
Object-like value to split |
| fn | Function |
Predicate with which to split items |
RETURNS
[truthy, falsy]
USAGE
partition([true, false, true, false], v => v === true)// -> [[true, true], [false, false]]partition({ keyOne: true, keyTwo: false }, v => v === true)// -> [{ keyOne: true }, { keyTwo: false }]partition('some arbitrary string', v => v === ' ')// -> [' ', 'somearbitrarystring']partition(new Map([['keyOne', true], ['keyTwo', false]]), v => v === true)// -> [ Map {'keyOne' => true}, Map {'keyTwo' => false} ]partition(new Set(['Joe', 'Jerry', 'Rick', 'Bob']), v => v.startsWith('J'))// -> [ Set {'Joe', 'Jerry'}, Set {'Rick', 'Bob'} ]
pathDotsutilities v1.0.0
pathDots(value)
Converts arrays of object path segments into dot-notated paths.
If value is a string, brackets will be normalized to dots.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | string | string[] |
String using dot or bracket syntax, or an array of path segments |
RETURNS
boolean
USAGE
pathDots(['a', 'b', 'c', '0'])// -> 'a.b.c.0'pathDots('a[1].b.c[0]')// -> 'a.1.b.c.0'
SEE ALSO
pathLinksutilities v1.0.0
pathLinks(value)
Convert value (a dot or bracket notated string) to an array of object path
segments. If it's already an array it will just be returned.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | string | string[] |
String using dot or bracket syntax, or an array of path segments |
RETURNS
boolean
USAGE
pathLinks('a[1].b.c[0]')// -> ['a', '1', 'b', 'c', '0']pathLinks(['a', 'b', 'c', '0'])// -> ['a', 'b', 'c', '0']
SEE ALSO
pipeasyncfunctions v1.0.0
pipe(a, b)
Run a set of functions in series using the output of each as the input to the next. The first value is allowed to be of any kind - if it is not a function it is simply passed as the argument to the second item. Subsequent non-function items are ignored.
Because pipe handles Promise-returning functions, it will
always return a Promise in order to maintain a consistent API
even if all given functions & values are synchronous.
ARGUMENTS
| name | type | description |
|---|---|---|
| ...inputs | Function[] |
Set of functions to pipe through |
RETURNS
Promise
USAGE
pipe('hello',str => str.toUpperCase(),str => str.split('').join('-')).then(result => {console.log(result)// -> 'H-E-L-L-O'})async function getUserData (name) {return { name, favoriteColor: 'blue' }}pipe(name => getUserData(name),user => user.favoriteColor === 'blue').then(result => {console.log(result)// -> true})
randomnumberscollections v1.0.0
random(value, bound)
If value is an array or object, return a random value. If it's a number
and bound is absent, return a random number between 0 and value. If
bound is provided, return a random value between value and bound.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | array | object | number |
Collection to sample or a bounding number |
| bound | number |
Used as the upper bound when value is a number |
RETURNS
any
USAGE
random([1, 2, 3])// -> randomly chosen element from the arrayrandom({ one: 1, two: 2, three: 3 })// -> value from a randomly chosen key in the objectrandom(10)// -> randomly chosen number between 0 and 10random(-5, 5)// -> randomly chosen number between -5 and 5
rangenumbers v1.0.0
range(...args)
Create an array of numbers beginning at and including start
through and including end.
If step is provided, it is used as the increment between
each element of the resulting array. This can affect the number
of values in the result.
ARGUMENTS
| name | type | description |
|---|---|---|
| start | number |
Value at which to start the range |
| end | number |
Value at which to end the range |
| step | number |
Increment between each element |
RETURNS
number[]
USAGE
range(0, 10)// -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]range(0, 10, 2)// -> [0, 2, 4, 6, 8, 10]
SEE ALSO
reducecollections v1.0.0
reduce(collection, fn, initial)
Universal version of native Array#reduce that works on pretty much any
iterable - arrays & array-likes, objects, Sets, Maps, strings, custom
iterables, etc.
ARGUMENTS
| name | type | description |
|---|---|---|
| collection | Iterable |
Iterable-like object to reduce from |
| fn | Function |
Function that builds the accumulator with each iteration |
| initial | any |
Value first passed to fn |
RETURNS
any
USAGE
let collection = { one: 1, two: 2, three: 3 }reduce(collection, (acc, cur) => acc + cur, 0)// -> 6collection = [1, 2, 3, 4, 5]reduce(collection, (acc, cur) => acc + cur, 0)// -> 15collection = 'foobar'fn(collection, (acc, cur) => {acc.splice(0, 0, cur)return acc}, [])// -> ['r', 'a', 'b', 'o', 'o', 'f']
SEE ALSO
reduceWhilecollections v1.0.0
reduceWhile(collection, predicate, fn, initial)
Works just like reduce but short-circuits when
predicate returns a falsy value.
ARGUMENTS
| name | type | description |
|---|---|---|
| collection | Iterable |
Iterable-like object to reduce from |
| predicate | Function |
Function that will stop iteration when returning a falsy value |
| fn | Function |
Function that builds the accumulator with each iteration |
| initial | any |
Value first passed to fn |
RETURNS
any
USAGE
const predicate = accumulator => accumulator !== 3const reducer = (acc, cur) => acc + curconst object = { one: 1, two: 2, three: 3 }reduce(object, reducer, 0)// -> 6reduceWhile(object, predicate, reducer, 0)// -> 3
SEE ALSO
sleepasyncutilities v1.0.0
sleep(ms)
Similar to the built-in setTimeout but does not receive
a function to run when the time expires. Simply returns a
Promise that resolves after ms. Pairs well with await.
ARGUMENTS
| name | type | description |
|---|---|---|
| ms | number |
Amount of time to wait |
RETURNS
any
USAGE
async function foo () {console.log('start')await sleep(5000)console.log('done')}foo()// -> start// ... 5 seconds pass ...// -> done
snakeCasestrings v1.0.0
snakeCase(string)
Convert the given string to snake_case.
ARGUMENTS
| name | type | description |
|---|---|---|
| string | string |
Input string to convert to snake-case |
RETURNS
string
USAGE
snakeCase('A space separated string')// -> 'a_space_separated_string'snakeCase('camelCasedThing')// -> 'camel_cased_thing'snakeCase('already_snake_cased')// -> 'already_snake_cased'
mapcollections v1.0.0
map(collection, fn)
Universal version of native Array#map that works on pretty much any
iterable - arrays & array-likes, objects, Sets, Maps, strings, custom
iterables, etc.
The return value will be collection but each value will be the result
of applying fn at each iteration to the arguments value, key,
collection.
ARGUMENTS
| name | type | description |
|---|---|---|
| collection | object |
Iterable-like object to map over, applying fn on each iteration |
| fn | Function |
Callback applied to each item in collection |
RETURNS
any – same type as collection
USAGE
map({ one: 1, two: 2, three: 3 }, v => v + 1)// -> { one: 2, two: 3, three: 4 }map([1, 3, 5, 7], v => v * -1)// -> [-1, -3, -5, -7]map('foobar', v => v + '-')// -> 'f-o-o-b-a-r-'
setobjects v1.0.0
set(object, path, value)
Sets the key at path to value on object and returns
the object. Deep property access is supported using both dot and
bracket syntax or an array of path segments.
ARGUMENTS
| name | type | description |
|---|---|---|
| object | object |
Object-like value to access |
| path | string | string[] |
String using dot or bracket syntax, or an array of path segments |
| value | any |
Value to which path will be set |
RETURNS
object
USAGE
const object = { key: 'value', nested: { inner: { deep: 'thing' } } }set(object, 'nested.inner.deep', 40)// -> { key: 'value', nested: { inner: { deep: 40 } } }
textCasestrings v1.0.0
textCase(string)
Convert the given string to text case.
ARGUMENTS
| name | type | description |
|---|---|---|
| string | string |
Input string to convert to text-case |
RETURNS
string
USAGE
textCase('snake-cased-string')// -> 'snake cased string'textCase('camelCasedThing')// -> 'camel cased thing'textCase('already text cased')// -> 'already text cased'
toArrayutilitiescollections v1.0.0
toArray(value, begin, end)
Alternative to the [].slice.call() method of converting
values to arrays. It will convert array-like objects and
wrap values in an array that don't coerce.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to convert |
| begin | Number |
Optional index at which to begin a slice |
| end | Number |
Optional index at which to end a slice |
RETURNS
any
USAGE
toArray(undefined)// -> []toArray(null)// -> [null]toArray((function () { return arguments })(1, 2, 3))// -> [1]toArray(4)// -> [4]toArray(true)// -> [true]toArray(false)// -> [false]toArray({})// -> [{}]toArray([])// -> []toArray([1, 2, 3, 4, 5], 2)// -> [3, 4, 5]toArray([1, 2, 3, 4, 5], 2, -1)// -> [3, 4]
toBooleanutilitieslogic v1.0.0
toBoolean(value, smart)
Return a boolean based on value - the usual falsy values
and empty values will return false, while truthy values
return true.
When smart is true and value is a string, it will
be checked for the strings 'true' and 'false' and coerced to
a boolean accordingly.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to convert |
| smart | boolean |
Whether to coerce value based on strings 'true' or 'false' |
RETURNS
boolean
USAGE
// examples of `true` cases:toBoolean(true)toBoolean(1)toBoolean('true')toBoolean('false')toBoolean(new Date())toBoolean({ one: 1 })toBoolean([1, 2, 3])// examples of `false` cases:toBoolean(false)toBoolean(null)toBoolean(undefined)toBoolean('')toBoolean(0)toBoolean({})toBoolean([])
toEmptyutilities v1.0.0
toEmpty(type)
Return an empty value matching the kind supplied by type,
which is either a string representing its kind or any object.
ARGUMENTS
| name | type | description |
|---|---|---|
| type | `` |
RETURNS
any
USAGE
toEmpty('array')// -> []toEmpty('object')// -> {}toEmpty('boolean')// -> falsetoEmpty(null)// -> nulltoEmpty([1, 2, 3, 4])// -> []
toNumberutilitiesnumbers v1.0.0
toNumber(value, round)
Convert the given value to a number. For example, this function applied to
a collection of almost any kind will return the number of elements in the
collection.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to convert |
| round | boolean |
Whether to round the output to an integer |
RETURNS
number
USAGE
toNumber(1)// -> 1toNumber(1.3345)// -> 1.3345const now = new DatetoNumber(now) === now.valueOf()// -> truetoNumber({ one: 1, two: 2 })// -> 2toNumber([1, 2, 3])// -> 3toNumber('string')// -> 6toNumber(39.354, true)// -> 39
toObjectutilitiescollections v1.0.0
toObject(value)
Ensure an object is returned, by converting value if possible
or by returning an empty object otherwise. If value is already
an object it is simply returned. null & undefined will produce
an empty object.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to convert |
RETURNS
object
USAGE
toObject(['one', 'two', 'three'])// -> { one: 'one', two: 'two', three: 'three' }toObject(3)// -> { '3': 3 }toObject(new Map([['keyOne', 'valueOne'], ['keyTwo', 'valueTwo']]))// -> { keyOne: 'valueOne', keyTwo: 'valueTwo' }toObject(true)// -> { 'true': true }toObject('fly')// -> { 'fly': 'fly' }toObject(null)// -> { 'null': null }toObject(undefined)// -> { 'undefined': undefined }toObject(new Date)// -> {}
SEE ALSO
toObjectWithutilitiescollections v1.0.0
toObjectWith(value, fn)
Ensure an object is returned, by converting value if possible
or by returning an empty object otherwise. If value is already
an object it is simply returned. null & undefined will produce
an empty object.
Works just like toObject, but receives a function
that allows for transforming the values of the resulting object.
ARGUMENTS
| name | type | description |
|---|---|---|
| value | any |
Value to convert |
| fn | Function |
Function accepting incoming elements and returning values of the output object |
RETURNS
object
USAGE
toObjectWith(['one', 'two', 'three'], value => value)// -> { one: 'one', two: 'two', three: 'three' }toObjectWith(['one', 'two', 'three'], value => {switch (value) {case 'one': return [1]case 'two': return [2]case 'three': return [3]}})// -> { one: [1], two: [2], three: [3] }
SEE ALSO