7.8.1
Apply a list of function (extract functions) on the same input and use the results as parameters for a final accumulator function.
(...any)
Function params
any
:
const divide = () => {}
const sum = () => {}
const count = () => {}
converge(divide, [sum, count], [1, 2, 3, 4, 5, 6, 7])
// => 4
Call fn
over each element of an array
undefined
:
Identity function
(any)
Source input
any
:
Iterates over an array and applies a function on each element, returning a new array with the transformed elements.
(Array)
Source array to iterate over
Array
:
Returns new instance
const inc = x => x + 1
map(inc, [1, 2])
// => [2, 3]
map([inc, inc], [1, 2])
// => [3, 4]
Matrix version of "map". Iterates over a two-dimensional array and applies a function on each element, returning a new matrix with the transformed elements.
const inc = x => x + 1
mapMatrix(inc, [[1, 2], [3, 4]])
// => [[2, 3], [4, 5]]
mapMatrix([inc, inc], [[1, 2], [3, 4]])
// => [[3, 4], [5, 6]]
Performs left-to-right function composition. The leftmost function may have any arity, the remaining functions must be unary.
any
:
pipe(inc, inc)(2)
// => 4
Get value from obj property
(any)
Value to return if not found
(Object)
Source object
(...any)
Function params
any
:
read("lorem")({ lorem: "ipsum" })
// => "ipsum"
read("not-exist")({ lorem: "ipsum" })
// => undefined
read("not-exist-with-default", "dolor", { lorem: "ipsum" })
// => "dolor"
read(["a", "b"])({ a: { b: "c" } })
// => "c"
read(["a", "test"])({ a: { b: "c" } })
// => undefined
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 accumulator value
(Array)
Source input
(...any)
Function params
any
:
const sum = (acc, item) => acc + item
reduce(sum, 0, [1, 2])
// => 3
Curried funtion that always returns the input given
(any)
Something, anything
any
:
Shallow clone of an object, setting or overriding a property with the given value
Object
:
write( "a", "lorem" )( { b: "ipsum" } )
// => { a: "lorem", b: "ipsum" }
Get all but first element from array
any
:
bottom([1, 2, 3])
// => [1, 2]
bottom([1]), bottom([])
// => []
bottom(2, [2, 3])
// => [2, 3]
bottom(2)([1, 2, 3])
// => [2, 3]
Count the number of elements that satisfies a function
number
:
const scores = [{
name : "Bob",
score : 1,
subject: "Math"
}, {
name : "Alice",
score : 10,
subject: "Math"
}, {
name : "Hatter",
score : 10,
subject: "Math"
}]
count(element => element.score === 10)(scores)
// => 2
Count elements in array or object that match object
(Object)
Match object
number
:
const scores = [{
name : "Bob",
score : 1,
subject: "Math"
}, {
name : "Alice",
score : 10,
subject: "Math"
}, {
name : "Hatter",
score : 10,
subject: "Math"
}]
countWith(
{ score: gt(5) },
scores
)
// => 2
Remove repeating values
(Array)
Source input array
Array
:
distinct([1, 1, 2])
// => [1, 2]
Filter elements matching a predicate
(Function)
Predicate functions
Array
:
Filter elements matching an object
(Object)
The function
Array
:
Find the first element that matches a predicate
any
:
const comments = [{id: 1, body: ""}, {id: 2, body: "dolor"}]
find(item => item.body === "dolor")(comments)
// => {id: 2, body: "dolor"}
find([get("body"), equals("dolor")], null, comments)
// => {id: 2, boby: "dolor" }
Find the first element that matches an object
(Object)
Match object
(any)
Return if no item found
(Array)
Source array to iterate over
any
:
First element found or undefined
const comments = [{id: 1, body: ""}, {id: 2, body: "dolor"}]
findWith({id: 2})(comments)
// => {id: 2, body: "dolor"}
find({id: "404"}, {default: "value"}, comments)
// => {default: "value"}
Get left most element of array
(Array)
The source
any
:
first([1, 2, 3])
// => 1
first([])
// => undefined
Recursively concat all arrays intro a single array
Array
:
1 level deep array
flatten([1, [2], [3, [4]]])
// => [1, 2, 3, 4]
flatten({test: {a: 1, b: {c: 2}}})
// => {
test__a: 1,
test__b__c: 2
}
Get right most element of array
(Array)
The source
any
:
last([1, 2, 3])
// => 3
last([])
// => undefined
Split an array based on a predicate function.
Take A[]
and return 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
.
(Function)
A predicate function.
Array<Array, Array>
:
partition(x => x % 2 === 0)([1, 2, 3, 4, 5])
// => [[2, 4], [1, 3, 5]]
Split an array based on object matching
Take A[]
and return 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
.
(object)
A predicate function.
Array<Array, Array>
:
partitionWith({comments: is}, [{id: 1}, {id: 2, comments: []}])
// => [[{id: 1}], [{id: 2, comments: []}]]
Returns a partial copy of an object containing only the keys specified. If the key does not exist, the property is ignored.
(...any)
(Object | Array<Object>)
:
pluck(
["id", "name"],
{
id: 2,
name: "lorem",
description: "lorem ipsum"
}
)
// => {id: 2, name: lorem}
Remove element(s) from array by value or by predicate
Array
:
remove(3)([1, 2, 3])
// => [1, 2]
remove(_ => _ === 3)([1, 2, 3])
// => [1, 2]
Remove element(s) by matching object
Array
:
removeWith(
{
tag: not(is)
},
[
{id: 1, tag: 2},
{id: 2}
]
)
// => [{id: 1, tag: 2}]
Sort primitive array
Array
:
sort([3, 2, 1])
// => [1, 2, 3]
sort("desc", [1, 2, 3])
// => [3, 2, 1]
Sort array using custom function
Array
:
sortBy((a, b) => a.id - b.id, [{id: 2}, {id: 1}])
// => [{id: 1}, {id: 2}]
Sort an array of objects by multiple fields
Array
:
sortWith({position: "asc"},
{ 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 },
//]
Get all but last element from array
any
:
top([1, 2, 3])
// => [1, 2]
top([1]), top([])
// => []
top(2, [2, 3])
// => [2, 3]
top(2)([1, 2, 3])
// => [2, 3]
Test if all elements of array satisfy a function
(Array)
Source array to iterate over
boolean
:
True if all elements pass, otherwise false
all(isNumber)([1, 2, 3])
// => true
all(is, [1, "asd", null])
// => false
Test if all elements in array match object
boolean
:
True if all elements match, otherwise false
allWith(isNumber)([1, 2, 3])
// => true
allWith(is, [1, "asd", null])
// => false
Test if at least one element in array matches predicate
boolean
:
True if at least one element passes, otherwise false
any(isNumber)([1, "string", NaN])
// => true
any([get("id"), is], [{title: ""}, {}])
// => false
Test if at least one element in array matches object
boolean
:
True if at least one element pass, otherwise false
anyWith({ comments: is })([{id: 1}, {id: 2, comments: []}])
// => true
anyWith({ tags: is })([{id: 1}, {id: 2, comments: []}])
// => false
Test if something is not null, undefined or NaN
(any)
Source variable
boolean
:
is(null) // => false
is(0) // => true
is(undefined) // => false
is("") // => true
is(false) // => true
is(NaN) // => false
Check if value is inside open or closed interval
boolean
:
between(2, 5)(5)
// => false
between(2, 5, {closed: true})(5)
// => true
Check if variable is considered empty
(any)
Source input
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
Check if a tripple-equals b (accounts for null, undefined and NaN)
boolean
:
equal(2)(2)
// => true
equal("2")(2)
// => false
equal(NaN)(NaN)
// => true
equal([1])([1])
// => 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
Functional if-then-else
any
:
when(isEven, increment, decrement)(5)
// => 6
when(isOdd, increment)(6)
// => 6
Get list with names of all own properties
Array<string>
:
List of property names
keys(["lorem", "ipsum"])
// => ["0", "1"]
keys({ foo: "bar", lorem: "ipsum"})
// => ["foo", "lorem"]
keys("foo"), keys(12), keys(null), etc
// => []
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 }
Returns a new list by extracting the same named property off all objects in the source list
(...any)
Array
:
pick("position")([{id: 1, position: 3}, {id:2, position: -1}])
// => [3, -1]
Create an object from two arrays, one containing keys, the other values. Both arrays will be trimmed to the smallest length.
Object
:
zipToObject([a, b])([1, 2]) // => { a: 1, b: 2 }
zipToObject([a], [1, 2]) // => { a: 1 }
Determine if two variables are structurally equal
boolean
:
True if inputs are structurally equal, false otherwise
deepEqual(
{b: 3, a: 2},
{a: 2, b: 3}
)
// => true
deepEqual(
{a :[1, 2]}
)(
{a: [2, 1]}
)
// => false
Calculate elapsed time between to dates. In days, hours, minutes and seconds
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 }
Group an array of objects by field.
(string)
The field to index by. Value will be cast to string before indexing.
(Array)
Input array
Array<Array>
:
groupBy("user_id")([
{id: 1, user_id: 2},
{id: 2, user_id: 3},
{id: 3, user_id: 2},
{id: 4, user_id: null},
] )
// => [
// [{id: 1, user_id: 2}, {id: 3, user_id: 2}],
// [{id: 2, user_id: 3}],
// [{id: 4, user_id: null}],
// ]
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},
// }
Count the number of occurances of each element
(Array)
Source input
Object
:
Count the number of occurances of each object by a field
(string)
The field
Object
:
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 }
Return an array of constructor function names based on the prototype chain
Array<string>
:
Replicate try/catch using a tryer and catcher function
(Function)
Try to do something with source input
(Function)
Run if tryer throws exception
any
:
tryCatch(inc)(10)
// => 11
tryCatch(
() => { throw new Error("Tryer error") },
(error, source) => inc(source)
)(10)
// => 11
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".
(any)
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"
Create a wrapper function that is invoked once every time interval, regardless of how many times is called.
(Function)
Function
:
const thottledMouseMove = throttle(mouseMove, { wait: 100 })
// render
<input onMouseMove={thottledMouseMove} ... />
Create a wrapper functions that is invoked only after some time since the last call.
(Function)
Function
:
Wrapper function that calls
fn
after
wait
passed without calling
const debouncedAutocomplete = debounce(autocompleteFromAPI, { wait: 100 })
// render
<input onChange={debouncedAutocomplete} ... />
Check if a string is a valid URI based on RFC3986
(string)
boolean
:
isURI("lorem")
// false
isURI("http://www.ietf.org/rfc/rfc2396.txt")
// true
Proxy input and print to console.log. Useful for debugging pipe chains.
any
:
Performs left-to-right function composition. The leftmost function may have any arity, the remaining functions must be unary.
Functions can return a Promise, behaving like Promise.sequence.
Promise<any>
:
const inc = input => input + 1
const incP = input => Promise.resolve(input + 1)
pipeP(incP, inc)(2).then(result => {
// => result = 4
})
Creates a new instance of the object with same properties than original. Will not inherit prototype, only own enumerable properties.
(any)
Source input value
any
:
New instance of source
let x = {a: [1]}
clone(x)
// => {a: [1]}
close(x) === x
// => false
Return an array of fixed size containing a specified value or function result
Array
:
repeat(2)(3)
// => [2, 2, 2]
repeat(index => index + 1, 3)
// => [1, 2, 3]
Partially apply a function
(Function | 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.
const sum = (a, b) => a + b
curry(sum)(1)(2) = 3
Returns a copy of the object or array with all null or undefined values removed.
(Array | Object)
:
compact([1, null, undefined, {}])
// => [1, {}]
compact({
a: "Lorem Ipsum",
b: null,
c: undefined,
d: false,
f: lambda,
}),
// => {
// a: "Lorem Ipsum",
// d: false,
// f: lambda
// }
Functional case statement.
(Function
= i
)
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
Array
:
Object
:
(Object | Array<Object>)
:
Get list with names of all own properties
Array<string>
:
List of property names
values(["lorem", "ipsum"])
// => ["lorem", "ipsum"]
values({ foo: "bar", lorem: "ipsum"})
// => ["bar", "ipsum"]
values("foo"), values(12), values(null), etc
// => []
Object
:
(Object | Array<Object>)
:
Rename keys inside an object
(...any)
(Object | Array<Object>)
:
rename({ old: "new" }, { old: 42 })
// => { new: 42 }
rename({ old: "new" }, [{ old: 42 }, { old: 41 }])
// => [{ new: 42 }, { new: 41 }]
Get a subset array using offset and limit
Array
:
page({
offset: 1,
limit: 5
})([1, 2, 3, 4, 5, 6, 7, 8])
// => [2, 3, 4, 5, 6]
Add elements at end of array
Array
:
push(2)([1]) // => [1, 2]
push(2, 4)([1]) // => [1, 2, 4]
Find the maximum value in a source array
number
:
max([-1, 1, 10, 3])
// => 10
const fn = element => (new Date(element.time))
const input = [
{ time: "2018-05-15T11:20:07.754110Z" },
{ time: "2018-06-11T09:01:54.337344Z" },
{ time: "2018-06-08T08:26:12.711071Z" },
]
max(fn, input)
// => {time: "2018-06-11T09:01:54.337344Z"}
Find the minimum value in a source array
number
:
min([-1, 1, 10, 3])
// => -1
const fn = element => ( new Date( element.time ) )
const input = [
{ time: "2018-05-15T11:20:07.754110Z" },
{ time: "2018-06-11T09:01:54.337344Z" },
{ time: "2018-06-08T08:26:12.711071Z" },
]
min(fn)(input)
// => {time: "2018-05-15T11:20:07.754110Z"}
Array
:
Move element from one position to another
(...any)
Array
:
move(0, 1, [1, 2])
// => [2, 1]
Remove elements from end of array
Array
:
Add array or element at the end of array
Array
:
append([1])([4, 5])
// => [1, 4, 5]
Add array or element at begining of array
Array
:
prepend([1])([4, 5])
// => [1, 4, 5]
Add element if not exists, remove otherwise
Array
:
toggle(1)([1, 2])
// => [2]
toggle(1, [2])
// => [1, 2]
Replace substring in string
string
:
Replace element in array (shallow equal)
Array
:
Replace substring if source is string, replace element (shallow equal) if source is Array
(string | Array)
:
Replace object element in array using filter object
(Object)
Filter object to match against each element
(Object)
Object to replace matching elements
Array
:
replaceWith(
{id: 2},
{id: 2, title: "boss", isBoss: true}
)([
{id: 2, title:"minion"}
{id: 3, title:"minion"}
])
// => [
// {id: 2, title:"boss", isBoss: true},
// {id: 3, title:"minion"}
// ]
replaceWith({ id: 2 }, item => ({
...item,
content: ["new", "updated", "field"],
}))([
{ id: 1, name: "foo", content: [] },
{ id: 2, name: "bar", content: [] },
])
// [
// { id: 1, name: "foo", content: [] },
// { id: 2, name: "bar", content: ["new", "updated", "field"] },
// ],
Find the position the first element that satisfies a predicate function
number
:
Position of found element or -1 if not found
const comments = [{id: 1, body: ""}, {id: 2, body: "dolor"}]
findIndex(item => item.body === "lorem")(comments)
// => -1
findIndex([get("body"), equals("dolor")], null, comments)
// => 1
Combine two arrays into one a set (array of unique items), composed of items from both arrays.
The function starts with the distinct items from aList and each item of bList will be searched using a shallow equal. If found, it will be discarded.
Array<any>
:
join([1, 1, 2, 3, 3], [3, 3, 4, 4, 5])
// => [1, 2, 3, 4, 5]
Combine two arrays into one a set (array of unique items), composed of common items from both arrays.
The function starts with an empty array and each item of bList will be searched in aList using a shallow equal. If it's found, it's also checked if it has not been already added.
Array<any>
:
intersect([1, 2, 3, 3], [3, 3, 4, 5])
// => [3]
Combine two arrays into one a set (array of unique items), composed of common items from both arrays. Allow custom predicate and merge functions.
The function starts with an empty array and each item of bList will be searched in aList using a shallow equal. If it's found, it's also checked if it has not been already added.
Array<any>
:
intersectBy(
(a, b) => a.id === b.id,
(a, b) => ({ ...a, ...b }),
[
{ id: 1, lorem: "ipsum" },
{ id: 2, foo: "bar1" },
{ id: 2, foo: "bar2" },
],
[
{ id: 2, comments: [] },
{ id: 3, comments: [] },
]
)
// => [{ id: 2, foo: "bar1", comments: [] }]
Substract one
(number)
Input number
number
:
dec(2)
// => 1
Add one
(number)
Source input
number
:
inc(2)
// => 3
Grater compare.
boolean
:
gt(10)(4)
// => false
gt(10, 14)
// => true
Less compare.
Since this will mostly be used in pipe, the first param in the curry chain is the second operand.
boolean
:
lt(10)(4)
// => true
lt(10)(14)
// => false
Generate random number between interval
number
:
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"]
Split an array into multiple arrays of set size
Array<Array>
:
split(2, [1, 2, 3, 4])
// [[1, 2], [3, 4]]
Test if string starts with substring
boolean
:
startsWith("lorem", "lorem ipsum")
// => true
startsWith("lorem", ["lorem", "ipsum"])
// => true
startsWith("dolor")("lorem ipsum")
// false
Test if string ends with substring
boolean
:
endWith("ipsum", "lorem ipsum")
// => true
Convert string to lower case
(string)
string
:
toLower("Lorem Ipsum")
// "lorem ipsum"
Convert string to upper case
(string)
string
:
toUpper("Lorem Ipsum")
// "LOREM IPSUM"
Remove char from beginning and end of string
string
:
trim()(" lorem ")
// => "lorem"
trim("-", "-- lorem -")
// => " lorem "
Test if string contains substring
boolean
:
contains("ipsum")("lorem ipsum")
// => true
Unite all elements of an array into a string
string
:
unite(",", ["lorem", "ipsum"])
// => "lorem,ipsum"
Make safe for RegExp'ing
(string)
Source string
string
:
escapeRegExp( "lorem. ipsum [dolor]" )
// => "lorem \\. ipsum \\[dolor\\]"