0.34.0
Test if all elements of array satisfy function
boolean
:
True if all objects satisfy, false otherwise
all(isNumber)([1, 2, 3])
// => true
all(is)([1, "asd", null])
// => false
Test if object properties match all objects in input array
boolean
:
True if all objects match, false otherwise
all({
id: isString
})([
{ id: "uuid1", name: "foo"}
{ id: "uuid2", name: "bar"}
])
// => true
Test if at least one element of array satisfies function
boolean
:
True if at least one object passes, false otherwise
any(isNumber)([1, "string", NaN])
// => true
any(is)([null])
// => false
Test if object properties match any object in input array
boolean
:
True if at least one object matches, false otherwise
anyBy({
id: isNumber,
name: "lorem",
})([
{ id: "uuid", name: "lorem" },
{ id: 2, name: "foo" },
{ id: 3, name: "lorem", foo: "bar" },
])
// => true
Functional case statement.
(any)
List of 2-tuples of functions (if, then)
(any)
Function to call if no condition matches. Defaults to identity.
(any)
Value to check
any
:
The result of calling the first matching then function or the
otherwise function on the input.
cases([
[x === 0, x => x * 2],
[x === 1, x => x],
], x => x + 1)(2) = 3
Merge two arrays/values into one array
Array
:
Array with concatenated values
concat([1])([4, 5])
// => [1, 4, 5]
concat(1)(4)
// => [1, 4]
Creates a new instance of the object with same properties than original. Will not inherit prototype, only own enumerable properties.
(any)
Input value
any
:
Cloned value
let x = {a: [1]}
clone(x)
// => {a: [1]}
close(x) === x
// => false
Test if string contains substring
boolean
:
contains("ipsum")("lorem ipsum")
// => true
Count items in array that satisfies a function
number
:
Number of items that satisfied
fn
count([1, 2, 3])
// => 3
count(
item => item.score === 10
)([
{ name: "Bob", score: 1, subject: "CS" },
{ name: "Alice", score: 10, subject: "Math" },
{ name: "Hatter", score: 10, subject: "Math"}
])
// => 2
Count objects that match
number
:
Number of objects that match
subset
countBy({
subject: value => value === "Math"
score: value => value > 5
})([
{ name: "Bob", score: 1, subject: "CS" },
{ name: "Alice", score: 10, subject: "Math" },
{ name: "Hatter", score: 10, subject: "Math"}
])
// => 2
Partially apply a function.
(any)
The function to apply
(any)
The arguments to apply, in order
any
:
If the number of arguments provided is sufficient to call the function,
call the function and return the result. Otherwise, return a new function
which takes additional parameters, returning the result of calling
curry
on the function with the provided parameters.
curry((a, b) => a + b)(1)(2) = 3
Convert a curried function of arity n to a simple function with n parameters.
(any)
The function to apply
(any)
The arguments to apply, in order
any
:
The result of calling the function on each argument in turn,
until a non-function is the return value. If an insufficient number
of arguments are provided, return the partially applied function.
uncurry(a => b => c => a + b * c)(1, 2, 3) = 7
Call function after wait
milliseconds have elapsed
(Function)
Source function
Function
:
Wrapper function that calls
fn
after
wait
passed without calling
// constructor
this.debouncedAutocomplete = debounce(autocompleteFromAPI, {
wait: 100,
bind: this
})
// render
<input onChange={this.debouncedAutocomplete} ... />
Determine a variable's type. Looks only for Array, Object and RegExp. Everything else are "Primitive"
Not using ../type/type.js
added ~300k ops/sec
(mixed)
The source
string
:
Determine if 2 arrays are equal. Order counts: [1, 2] !== [2, 1]
boolean
:
Determine if 2 objects are equal
boolean
:
Determine if 2 regular expressions are equal
boolean
:
Shallow equal
(mixed)
Source input
(mixed)
Other source input
boolean
:
Determine if two variables are structurally equal (callable curried or uncurried)
boolean
:
True if inputs are deeply equal, false otherwise
deepEqual(
{ b: 3, a: 2 },
{ a: 2, b: 3 }
)
// => true
deepEqual(
{ a :[1, 2] }
)(
{ a: [2, 1] }
)
// => false
Remove duplicate values. Will use deepEqual
for comparison.
(Array)
Input array
Array
:
Duplicate free array
distinct([1, 1, 2])
// => [1, 2]
Calculate elapsed time between to dates. In days, hours, minutes and seconds (callable curried or uncurried).
Object
:
elapsedTime(
new Date("June 1, 2018 00:00:00")
)(
new Date("June 1, 2018 03:24:00")
)
// => { days: 0, hours: 3, minutes: 24, seconds: 0 }
Test if string ends with substring (callable curried or uncurried).
boolean
:
True if
source
ends with
search
, false otherwise
endWith("ipsum")("lorem ipsum")
// => true
Return an array of key-value pairs corresponding to the key-value pairs of an Object.
(any)
(implicit)
The object to return key-value pairs for
any
:
Key-value pairs (2-tuples)
entries({ id: 1, name: "test" }) = [["id", 1], ["name", "test"]]
Given an array of key-value tuples, construct an Object.
(any)
(implicit)
The key-value pairs to create the object from
any
:
An object with the given key-value pairs
fromEntries([["id", 1], ["name", "test"]]) = {
id: 1,
name: "test"
}
Make safe for RegExp'ing.
(string)
Input string
string
:
escapeRegExp( "lorem. ipsum [dolor]" )
// => "lorem \\. ipsum \\[dolor\\]"
Escape HTML special chars for safe rendering.
(string)
Input string
string
:
escapeHTML("<script>alert('HERE'S BOBBY')</script>")
// => "<script>alert('HERE'S BOBBY')</script>"
Filter items in array that satisfies test function
Array
:
filter(is)([1, 2, null, 3, undefined])
// => [1, 2, 3]
Filter items in array that match subset
Array<Object>
:
filterBy({
id: is,
})([
{ id: 1 },
{ id: null, name: "test" },
{ id: 3, foo: "bar" },
{ name: "test" },
])
// => [{ id: 1 }, { id: 3, foo: "bar" }]
Find the position of first element that matches the subset criteria
number
:
const comments = [{id: 1, body: ""}, {id: 2, body: "dolor"}]
findIndexBy({id: 2})(comments)
// => 1
findIndexBy({id: 3})(comments)
// => -1
Find the first element that satisfies test function.
(mixed | undefined)
:
First item that satisfied
fn
find(x => x % 2 === 0)([1, 2, 3, 4, 5])
// => 2
Find the first element that satisfies test function.
(mixed | undefined)
:
First item that satisfied
fn
findBy({
id: 2
})([
{ id: 1, foo: "bar" },
{ id: 2, foo: "ipsum" }
])
// => { id: 2, foo: "ipsum" }
Flatten a single level of an array.
(any)
Recursively concat all arrays intro a single array
(Array)
Array with nested arrays
Array
:
1 level deep array
flatten([1, [2], [3, [4]]])
// => [1, 2, 3, 4]
An alternate version of flatten that treats nested arrays as branches, constructing a set of arrays which represent the permutations of concatenations possible when taking a single value from each branch.
Unlike flatten, flattenBranches does not recurse on subelements.
WARNING: As a permutation function, it's subject to combinatorial explosion.
flattenBranches([1, 2, [3, 4]]) =
[[1, 2, 3], [1, 2, 4]]
flattenBranches([1, [2, 3], [4, 5]]) =
[[1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5]]
Reverse the first two parameters of a function.
(any)
Reverse the first two parameters of an uncurried function.
(any)
Call fn
over each element of an array
undefined
:
Get value from obj property
mixed
:
prop("lorem")({ lorem: "ipsum" }) // => "ipsum"
prop("not-exist")({ lorem: "ipsum" }) // => undefined
Group values from a list into a list of lists.
(any)
One of:
A
s and returning a boolean.A
is the type of the value at the given key.any
:
A function taking a
A[]
, and returning a
A[][]
.
Alternatively, a function taking a
Object[]
where the value at
grouper
is an
A
(if
grouper
is a string), and returning a
Object[][]
.
If grouper
was passed as a string, each sublist of the result will contain
objects where the value at key grouper
is equal (===
).
Otherwise, each sublist of the result will contain A
s which return
true
when passed pairwise to grouper
.
groupBy(x => y => x % 2 === y % 2)([1,2,3,4,5]) = [[1,3,5], [2,4]]
groupBy('id')([{ id: 1 }, { id: 2 }, { id: 1 }]) = [[{ id: 1 }, { id: 1 }], [{ id: 2 }]]
Grater compare
boolean
:
gt(4)(10)
// => false
gt(14)(10)
// => true
Check if value is in array
(mixed)
What to search for
(Array)
Haystack
boolean
:
True if has, false otherwise
has( 2 )( [ 1, 2 ] )
// => true
has( 3 )( [ 1, 2 ] )
// => false
has( elm => elm.id === 1 )([{}, {id: 1}])
// => true
Determine the count of all field's distinct values in a list of objects (aka histogram)
Object
:
const scores = [{
name : "Bob",
score : 1,
subject: "Math"
}, {
name : "Alice",
score : 10,
subject: "Math"
}, {
name : "Hatter",
score : 10,
subject: "Math"
}]
hist( "score" )( scores )
// => { "1": 1, "10": 2 }
Identity function
(mixed)
The input
mixed
:
Functional if-then-else
(Function)
Condition function
(Function)
Then function
(Function)
Else function, defaults to identity
(mixed)
Input
mixed
:
Index an array of objects by field. Only truthy fields will be indexed.
Object
:
indexBy("id")([
{id: 1, user_id: 2},
{id: 2, user_id: 3},
])
// => {
// 1: [{id: 1, user_id: 2}],
// 2: [{id: 2, user_id: 3}],
// }
Test if a variable holds something
(any)
Source variable
boolean
:
is(null) // => false
is(0) // => true
is(undefined) // => false
is("") // => true
is(false) // => true
is(NaN) // => false
Determines something is empty
(Any)
Something to check if empty
boolean
:
True if empty, False otherwise
isEmpty({}) // true
isEmpty(1) // false
isEmpty(false) // false
isEmpty("") // true
isEmpty(null) // true
isEmpty(undefined) // true
isEmpty([]) // true
isEmpty(NaN) // true
isEmpty(/[A-z]/) // false
isEmpty(new Date()) // false
isEmpty(() => {}) // false
isEmpty(Promise.resolve() // false
Determines if one object's properties are equal to another
boolean
:
True if all "subset" properties are of equal (shallow
compare) value to properties in "source" object,
otherwise false
isMatch({
id: 2,
parentId: null,
})({
id: 2,
parentId: null
name: "John",
})
// true
isMatch({
"!parentId": null,
"name": "John",
})({
id: 2,
parentId: null,
name: "John",
})
// false
Test if a variable holds nothing
(any)
Source variable
boolean
:
isNot(null) // => true
isNot(NaN) // => true
isNot(undefined) // => true
isNot(0) // => false
isNot("") // => false
isNot(false) // => false
Join all elements of an array into a string
string
:
join( "," )( [ "lorem", "ipsum" ] )
// => "lorem,ipsum"
Return last element in array
(Array<T>)
Source array
T
:
Last element or undefined if empty source
last([1, 2, 3])
// 3
last([])
// undefined
Create a pair of lenses - functions for retrieving or updating the value at an object key.
The lens functions will throw errors if they are passed objects which are invalid for the lens.
(...any)
The path to the value to make lenses for. This must be flat.
any
:
A 2-tuple of lenses - the getter and the setter
lens("a", "b", "id")({ a: { b: { id: 1 } } }) = [get, set]
where get(obj) => 1
set(3)(obj) => { a: { b: { id: 3 } } }
A version of lens that allows nesting, allowing for the creation of multiple lenses simultaneously. Be careful with this one, it's subject to combinatorial explosion.
(...any)
_lenses("a", "b", ["id", "name"]) = [
lens("a", "b", "id")
lens("a", "b", "name")
]
_lenses("a", ["b", "c"], ["id", "name"]) = [
lens("a", "b", "id")
lens("a", "b", "name")
lens("a", "c", "id")
lens("a", "c", "name")
]
Make several lenses at once, which may be completely unrelated to one another.
Imagine we have an object:
{ a: { b: { id: 1, name: "Test" }, c: { banana: 1, message: "Error" } } }
(...any)
lenses(
["a", "b", ["id", "name"]],
["a", "c", "banana"]
) = [
[[getId, setId], [getName, setName]],
[getBanana, setBanana]
]
Less compare
boolean
:
lt(4)(10)
// => true
lt(14)(10)
// => false
Iterate over an input list, calling fn
for each element, return a new
array
Array
:
Find the maximum value in a source array
number
:
max([-1, 1, 10, 3])
// => 10
const fn = element => ( new Date( element.time ) )
const source = [
{ time: "2018-05-15T11:20:07.754110Z" },
{ time: "2018-06-11T09:01:54.337344Z" },
{ time: "2018-06-08T08:26:12.711071Z" },
]
max(fn)(source)
// => {time: "2018-06-11T09:01:54.337344Z"}
Merge two objects, provided a function to decide what to do with overlapping keys.
(any
= {}
)
(any
= defaultMergeFn
)
The merging function to use by default (if a specific function is not
provided for a key in the fn object.) By default, the second value
overwrites the first value unless the second value is undefined.
(any)
An Object of curried functions taking two values, where the function
at a key describes how to merge duplicate values at the key.
(any)
The first object
(any)
The second object
any
:
An object with properties merged from a and b
mergeTwoWith({ isLoading: a => b => a || b })({
isLoading: false,
a: undefined,
b: 2
})({
isLoading: true,
a: "test",
b: undefined
}) = {
isLoading: true,
a: "test",
b: 2
}
Merge two objects. Keys from the second object corresponding to undefined values will be ignored, otherwise same-named keys from the second object will take priority.
(any)
The first object
(any)
The second object
any
:
An object with the props from both input objects merged together
mergeTwo({ id: 1, name: "test" })(
{ id: undefined, name: "test2", error: "Error" }
) = { id: 1, name: "test2", error: "Error" }
Merge n objects, provided functions which describe what to do in the case of overlapping keys.
(any)
(any)
The merging function to use by default
(any)
An Object of curried functions taking two values, where the function
at a key describes how to merge duplicate values at the key.
(any)
The first object
(any)
The second object
any
:
An object with properties merged from all source objects
mergeWith({ isLoading: a => b => a || b })({
isLoading: false,
a: undefined,
b: 2
}, {
isLoading: true,
a: "test",
b: undefined
}, {
isLoading: false,
a: "test2",
c: false
}) = {
isLoading: true,
a: "test2",
b: 2,
c: false
}
Combine from left to right, 2 or more objects into a new single one. Properties will be shallow copied. Those with the same name will be overwriten by right most object.
Object
:
merge({a: "lorem"}, {b: "ipsum", c: 41}, {c: 42, b: undefined})
// => { a: "lorem", b: "ipsum", c: 42 }
Find the minimum value in a source array
number
:
min([-1, 1, 10, 3])
// => -1
Split a list based on a predicate function.
(any)
A predicate function.
any
:
A function taking a
A[]
and returning a two-tuple of
A[]
s.
The first element of the tuple consists of elements for which
the predicate returned
true
, the second of elements for which
it returned
false
.
partition(x => x % 2 === 0)([1,2,3,4,5]) = [[2,4],[1,3,5]]
Returns a partial copy of an object containing only the key-value pairs for which the provided predicate function returns true.
Returns a partial copy of an object containing only the keys specified. If the key does not exist, the property is ignored.
(any)
The properties to keep from the source
(any)
(implicit)
The input object
any
:
The input object, minus any keys which
pick(["id", "name"])({id: 2, name: "lorem", description: "lorem ipsum"})
// => {id: 2, name: lorem}
Performs left-to-right function composition. The leftmost function may have any arity, the remaining functions must be unary.
(Array)
Array of functions, call each one in order with the
input of previous one's result
(Array)
Arguments array
mixed
:
pipe( inc, inc )( 2 )
// => 4
Returns a new list by extracting the same named property off all objects in the source list
number
:
pluck("position")([{id: 1, position: 3}, {id:2, position: -1}])
// => [3, -1]
Add element at end of array
(mixed)
Element to be added
(Array)
Array to add to
Array
:
push( 2 )( [ 1 ] ) // => [ 1, 2 ]
push( 2, 4 )( [ 1 ] ) // => [ 1, 2, 4 ]
Apply a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
(Function)
Reduce function
(Object)
Default value for the accumulator
(Array)
Source input
mixed
:
Remove value from array (strict equality check)
(mixed)
Value to remove
(Array)
Input array
Array
:
remove(2)([1, 2, 3])
// => [1, 3]
remove(null)([1, null, 2, 3, null])
// => [1, 2, 3]
Replace substring in string
string
:
Replace element in array (shallow equal)
(mixed)
The old elm
(mixed)
The new elm
Array
:
Replace substring if source is string, replace element (shallow equal) if source is Array
(string | Array)
:
Rename object properties.
(any)
A mapping from old names to new ones
(any)
(implicit)
The object to rename keys of
rename({
test: "test2"
})({ test: 2, unrelated: false }) = { test2: 2, unrelated: false }
Create an array of numbers
Array<number>
:
sequence(1)(1, 5) // [1, 2, 3, 4, 5]
sequence(3)(1, 5) // [1, 4]
sequence(-1)(2, -3) // [ 2, 1, 0, -1, -2, -3 ]
Shallow clone of an object, setting or overriding a property with the given value
Object
:
set( "a", "lorem" )( { b: "ipsum" } )
// => { a: "lorem", b: "ipsum" }
Sort array using custom function
Array
:
sort((a,b) => a.id-b.id)([{id:2}, {id: 1}])
// => [{id:1}, {id: 2}]
Sort an array of objects by a custom field
Array
:
sortBy( "position" )( [
{ id: 1, position: 3 },
{ id: 2, position: 2 },
{ id: 3 },
{ id: 4, position: 5 },
{ id: 5, position: null },
] )
// [
// { id: 2, position: 2 },
// { id: 1, position: 3 },
// { id: 4, position: 5 },
// { id: 5, position: null },
// { id: 3 },
//]
Splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
Array
:
split( "," )( "lorem,ipsum" )
// [ "lorem", "ipsum" ]
Return last element in array
(Array)
Source array
Array
:
All but first elements in array
tail([1, 2, 3])
// => [2, 3]
Call a function only if it hasn't been called in the last timeWindow
ms.
(function)
Function to be ran
(integer)
Time between each
fn
call
function
:
Either return
fn
if you've passed the
timeWindow
or return a timer that will
run the
fn
in
timeWindow
ms
Convert string to lower case
(string)
Source string
string
:
toLower("Lorem Ipsum")
// "lorem ipsum"
Add if not exists, remove otherwise
(mixed)
Toggable value
Array
:
toggle(1)([1, 2])
// => [2]
toggle(1)([2])
// => [1, 2]
Extract top elements from array
Array
:
top(2)([ 1, 2, 3 ])
// => [1, 2]
From ramda: Gives a single-word string description of the (native) type of a value, returning such answers as "Object", "Number", "Array", or "Null".
Does not attempt to distinguish user Object types any further, reporting them all as "Object".
(mixed)
Something to check type on
string
:
type({}) // "Object"
type(1) // "Number"
type(false) // "Boolean"
type("s") // "String"
type(null) // "Null"
type(undefined) // "Undefined"
type([]) // "Array"
type(/[A-z]/) // "RegExp"
type(new Date()) // "Date"
type(() => {}) // "Function"
type(Promise.resolve()) // "Promise"
Combine pairs of values from two lists by an arbitrary function. If the lists differ in length, the output will have the length of the shorter list.
(any)
The function to combine values by
(any)
The first list
(any)
The second list
zipWith(a => b => a * b)([2,3,4])([2,5,6]) = [4, 15, 24]
Combine pairs of values from two lists into a list of tuples.
If the lists differ in length, the output will have the length
of the shorter list. An alias of zipWith
where the fn
parameter
is a tupling function.
(any)
zip([2,3,4])([2,5,6]) = [[2, 2], [3, 5], [4, 6]]
Combine pairs of values from two lists matching a binary predicate into a list of arbitrary values.
(any)
A binary predicate function taking a value from each list and
returning a boolean
(any)
A function taking a value from each list and returning anything
(any)
The first list
(any)
The second list
zipFindWith(
a => b => (a * a) === b
)(a => b => a + b)([1, 2, 3])([4, 9, 1]) = [2, 6, 12]
Combine pairs of values from two lists matching a binary predicate
into a list of tuples. An alias of zipFindWith
where the fn
parameter
is a tupling function.
(any)
zipFind(
a => b => (a * a) === b
)([1, 2, 3])([4, 9, 1]) = [[1, 1], [2, 4], [3, 9]]
Combine pairs of values from two lists, where the second list must
be a list of objects and the value from the second list matches
a matching object (see isMatch
for details) generated by a value
from the first list. The values are combined via an arbitrary function.
An alias of zipFindWith
where the p
parameter is generated based
on the matching object returned by getMatchObj
.
(any)
zipByWith(
a => ({ aId: a.id })
)(a => b => merge(a, b))([
{ id: 1, color: 'red' },
{ id: 2, color: 'green' },
])([
{ aId: 2, fruit: 'pear' },
{ aId: 1, fruit: 'apple' },
]) = [
{ id: 1, aId: 1, color: 'red', fruit: 'apple' },
{ id: 2, aId: 2, color: 'green', fruit: 'pear' }
]
Combine pairs of values from two lists, where the second list must
be a list of objects and the value from the second list matches
a matching object (see isMatch
for details) generated by a value
from the first list. The values are combined into a tuple. An alias
of zipByWith
where values are combined by a tupling function.
(any)
zipByWith(
a => ({ aId: a.id })
)([
{ id: 1, color: 'red' },
{ id: 2, color: 'green' },
])([
{ aId: 2, fruit: 'pear' },
{ aId: 1, fruit: 'apple' },
]) = [
[{ id: 1, color: 'red' }, { aId: 1, fruit: 'apple' }],
[{ id: 2, color: 'green' }, { aId: 2, fruit: 'pear' }],
]
Create an object from two arrays, one containing keys, the other values. Bost arrays will be trimmed to the smallest length.
Object
:
zipToObj( [ a, b ] )( [ 1, 2 ] ) // => { a: 1, b: 2 }
zipToObj( [ a ] )( [ 1, 2 ] ) // => { a: 1 }