6.0.0Apply a list of function (extract functions) on the same input and use the results as parameters for a final accumulator function.
((Fn | Array<Fn>))
Accumulator or final aggreate function
((Fn | Array<Fn>))
List of functions to be applied on input
Any:
const divide = () => ...
const sum = () => ...
const count = () => ...
converge(divide, [sum, count], [1, 2, 3, 4, 5, 6, 7])
// => 4
Identity function
(mixed)
Source input
mixed:
Iterates over an array and applies a function on each element, returning a new array with the transformed elements.
((Fn | Array<Fn>))
Transform function called on each element
(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.
((Fn | Array<Fn>))
Transform function called on all elements
(Array<[]>)
Two-dimensional array to iterate over
Array<[]>:
New array instance
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]]
Get value from obj property
(mixed)
Value to return if not found
(object)
Source object
mixed:
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
mixed:
const sum = (acc, item) => acc + item
reduce(sum, 0, [1, 2])
// => 3
Get all but first element from array
mixed:
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 that match a predicate
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
((Fn | Array<Fn>))
Match function applied to each element
(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"}]
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
mixed:
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
mixed:
last([1, 2, 3])
// => 3
last([])
// => undefined
Split a list based on a predicate function
(Function)
A predicate function.
[[], []]:
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]]
Split a list based on object matching
(Object)
A predicate function.
[[], []]:
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
.
partitionWith({comments: is}, [{id: 1}, {id: 2, comments: []}])
// => [[{id: 1}], [{id: 2, comments: []}]]
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]
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:
remove(3)([1, 2, 3])
// => [1, 2]
remove(_ => _ === 3)([1, 2, 3])
// => [1, 2]
Get all but last element from array
mixed:
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 or undefined
(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 is equal to b (strict equality)
(mixed)
First value
(mixed)
Second value
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
(Function)
Condition
(Function)
Then function
(Function)
Else function, if not specified will return
source
mixed:
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 partial copy of an object containing only the keys specified. If the key does not exist, the property is ignored.
Object:
pick(["id", "name"])({id: 2, name: "lorem", description: "lorem ipsum"})
// => {id: 2, name: lorem}
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 }
Determine if two variables are structurally equal
(Any)
Source input
(Any)
Other source input
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
(Data)
Start date
(Data)
End date
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>:
Rename a file
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".
(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"
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
| Name | Description |
|---|---|
timeWindow.timeWindow any
(default 50)
|
|
timeWindow.bind any
(default null)
|
|
timeWindow.hasLastCall any
(default false)
|
function:
Either return
fn
if you've passed the
timeWindow
or return a timer that will
run the
fn
in
timeWindow
ms
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} ... />
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 | mixed):
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
Functional case statement.
(Array<[ifFn, thenFn]>)
List of 2-tuples of functions (if, then)
(Function)
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
Get a subset array using offset and limit
(Object
= {})
| Name | Description |
|---|---|
$0.offset any
(default 0)
|
|
$0.limit any
(default 10)
|
(number)
Start position
(number)
How many items
(Array)
Input array
Array:
page({
offset: 1,
limit: 5
})([1, 2, 3, 4, 5, 6, 7, 8])
// => [2, 3, 4, 5, 6]
Add element at end of array
Array:
push(2)([1]) // => [1, 2]
push(2, 4)([1]) // => [1, 2, 4]
Find max value using language operator
(Array)
Source input
mixed:
Find max value using function to transform element into numeric
mixed:
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"}
Find min value using language operator
(Array)
Source input
mixed:
Find min value using function to transform element into numeric
mixed:
Find the minimum value in a source array
number:
min([-1, 1, 10, 3])
// => -1
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" },
]
min(fn)(source)
// => {time: "2018-05-15T11:20:07.754110Z"}
{ lambda_description }
(number)
The count
Array:
{ description_of_the_return_value }
Remove elements from end of array
Array:
Merge two or more arrays into one
Array:
concat([1])([4, 5])
// => [1, 4, 5]
Add element if not exists, remove otherwise
(mixed)
Toggable value
Array:
toggle(1)([1, 2])
// => [2]
toggle(1)([2])
// => [1, 2]
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):
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"] },
// ],
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:
sortWith( "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 },
//]
Find the position the first element that satisfies a predicate function
((Fn | Array<Fn>))
Predicate applied to each element
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
Substract one
(number)
Source input
number:
dec(2)
// => 1
Add one
(number)
Source input
number:
inc(2)
// => 3
Grater compare.
Since this will mostly be used in pipe, the first param in the curry chain is the second operand.
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
integer:
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" ]
Test if string starts with substring
boolean:
startsWith("lorem")("lorem ipsum")
// => true
Test if string ends with substring
boolean:
endWith("ipsum")("lorem ipsum")
// => true
Convert string to lower case
(string)
Source string
string:
toLower("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
Join all elements of an array into a string
String:
join(",")(["lorem", "ipsum"])
// => "lorem,ipsum"
Make safe for RegExp'ing
(string)
Source string
string:
{ example }
escapeRegExp( "lorem. ipsum [dolor]" )
// => "lorem \\. ipsum \\[dolor\\]"