__ Function
A special placeholder value used to specify "gaps" within curried functions, allowing partial application of any combination of arguments, regardless of their positions.
If g
is a curried ternary function and _
is R.__
, the following are equivalent:
g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2, _)(1, 3)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
g(_, 2)(_, 3)(1)
var greet = R.replace('{name}', R.__, 'Hello, {name}!');
greet('Alice'); //=> 'Hello, Alice!'
add Math
-
Number
a
The first value.
-
Number
b
The second value.
The result of a + b
.
Adds two numbers (or strings). Equivalent to a + b
but curried.
R.add(2, 3); //=> 5
R.add(7)(10); //=> 17
addIndex Function
-
function
fn
A list iteration function that does not pass index/list to its callback
An altered list iteration function thats passes index/list to its callback
Creates a new list iteration function from an existing one by adding two new parameters to its callback function: the current index, and the entire list.
This would turn, for instance, Ramda's simple map
function into one that more closely
resembles Array.prototype.map
. Note that this will only work for functions in which
the iteration callback function is the first parameter, and where the list is the last
parameter. (This latter might be unimportant if the list parameter is not used.)
var mapIndexed = R.addIndex(R.map);
mapIndexed(function(val, idx) {return idx + '-' + val;}, ['f', 'o', 'o', 'b', 'a', 'r']);
//=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r']
adjust List
-
function
fn
The function to apply.
-
Number
idx
The index.
-
Array
list
An array-like object whose value at the supplied index will be replaced.
A copy of the supplied array-like object with
the element at index idx
replaced with the value
returned by applying fn
to the existing element.
Applies a function to the value at the given index of an array, returning a new copy of the array with the element at the given index replaced with the result of the function application.
R.adjust(R.add(10), 1, [0, 1, 2]); //=> [0, 11, 2]
R.adjust(R.add(10))(1)([0, 1, 2]); //=> [0, 11, 2]
all List
-
function
fn
The predicate function.
-
Array
list
The array to consider.
true
if the predicate is satisfied by every element, false
otherwise.
Returns true
if all elements of the list match the predicate, false
if there are any
that don't.
Acts as a transducer if a transformer is given in list position.
var lessThan2 = R.flip(R.lt)(2);
var lessThan3 = R.flip(R.lt)(3);
R.all(lessThan2)([1, 2]); //=> false
R.all(lessThan3)([1, 2]); //=> true
allPass Logic
-
Array
list
An array of predicate functions
-
*
optional
Any arguments to pass into the predicates
a function that applies its arguments to each of
the predicates, returning true
if all are satisfied.
Given a list of predicates, returns a new predicate that will be true exactly when all of them are.
var gt10 = function(x) { return x > 10; };
var even = function(x) { return x % 2 === 0};
var f = R.allPass([gt10, even]);
f(11); //=> false
f(12); //=> true
always Function
-
*
val
The value to wrap in a function
A Function :: * -> val.
Returns a function that always returns the given value. Note that for non-primitives the value returned is a reference to the original value.
var t = R.always('Tee');
t(); //=> 'Tee'
and Logic
-
*
a
any value
-
*
b
any other value
the first argument if falsy otherwise the second argument.
A function that returns the first argument if it's falsy otherwise the second argument. Note that this is NOT short-circuited, meaning that if expressions are passed they are both evaluated.
Dispatches to the and
method of the first argument if applicable.
R.and(false, true); //=> false
R.and(0, []); //=> 0
R.and(null, ''); => null
any List
-
function
fn
The predicate function.
-
Array
list
The array to consider.
true
if the predicate is satisfied by at least one element, false
otherwise.
Returns true
if at least one of elements of the list match the predicate, false
otherwise.
Acts as a transducer if a transformer is given in list position.
var lessThan0 = R.flip(R.lt)(0);
var lessThan2 = R.flip(R.lt)(2);
R.any(lessThan0)([1, 2]); //=> false
R.any(lessThan2)([1, 2]); //=> true
anyPass Logic
-
Array
list
An array of predicate functions
-
*
optional
Any arguments to pass into the predicates
A function that applies its arguments to each of the predicates, returning
true
if all are satisfied.
Given a list of predicates returns a new predicate that will be true exactly when any one of them is.
var gt10 = function(x) { return x > 10; };
var even = function(x) { return x % 2 === 0};
var f = R.anyPass([gt10, even]);
f(11); //=> true
f(8); //=> true
f(9); //=> false
ap Function
-
Array
fns
An array of functions
-
Array
vs
An array of values
An array of results of applying each of fns
to all of vs
in turn.
ap applies a list of functions to a list of values.
R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6]
aperture List
-
Number
n
The size of the tuples to create
-
Array
list
The list to split into
n
-tuples
The new list.
Returns a new list, composed of n-tuples of consecutive elements
If n
is greater than the length of the list, an empty list is returned.
R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]]
R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
R.aperture(7, [1, 2, 3, 4, 5]); //=> []
append List
-
*
el
The element to add to the end of the new list.
-
Array
list
The list whose contents will be added to the beginning of the output list.
A new list containing the contents of the old list followed by el
.
Returns a new list containing the contents of the given list, followed by the given element.
R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests']
R.append('tests', []); //=> ['tests']
R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']]
apply Function
- function fn
- Array args
Applies function fn
to the argument list args
. This is useful for
creating a fixed-arity function from a variadic function. fn
should
be a bound function if context is significant.
var nums = [1, 2, 3, -99, 42, 6, 7];
R.apply(Math.max, nums); //=> 42
arity Function
-
Number
n
The desired arity of the returned function.
-
function
fn
The function to wrap.
A new function wrapping fn
. The new function is
guaranteed to be of arity n
.
Wraps a function of any arity (including nullary) in a function that accepts exactly n
parameters. Unlike nAry
, which passes only n
arguments to the wrapped function,
functions produced by arity
will pass all provided arguments to the wrapped function.
var takesTwoArgs = function(a, b) {
return [a, b];
};
takesTwoArgs.length; //=> 2
takesTwoArgs(1, 2); //=> [1, 2]
var takesOneArg = R.arity(1, takesTwoArgs);
takesOneArg.length; //=> 1
// All arguments are passed through to the wrapped function
takesOneArg(1, 2); //=> [1, 2]
assoc Object
-
String
prop
the property name to set
-
*
val
the new value
-
Object
obj
the object to clone
a new object similar to the original except for the specified property.
Makes a shallow clone of an object, setting or overriding the specified property with the given value. Note that this copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference.
R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3}
assocPath Object
-
Array
path
the path to set
-
*
val
the new value
-
Object
obj
the object to clone
a new object similar to the original except along the specified path.
Makes a shallow clone of an object, setting or overriding the nodes required to create the given path, and placing the specific value at the tail end of that path. Note that this copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference.
R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}}
binary Function
-
function
fn
The function to wrap.
A new function wrapping fn
. The new function is guaranteed to be of
arity 2.
Wraps a function of any arity (including nullary) in a function that accepts exactly 2 parameters. Any extraneous parameters will not be passed to the supplied function.
var takesThreeArgs = function(a, b, c) {
return [a, b, c];
};
takesThreeArgs.length; //=> 3
takesThreeArgs(1, 2, 3); //=> [1, 2, 3]
var takesTwoArgs = R.binary(takesThreeArgs);
takesTwoArgs.length; //=> 2
// Only 2 arguments are passed to the wrapped function
takesTwoArgs(1, 2, 3); //=> [1, 2, undefined]
bind Function
-
function
fn
The function to bind to context
-
Object
thisObj
The context to bind
fn
to
A function that will execute in the context of thisObj
.
Creates a function that is bound to a context.
Note: R.bind
does not provide the additional argument-binding capabilities of
Function.prototype.bind.
both Logic
-
function
f
a predicate
-
function
g
another predicate
a function that applies its arguments to f
and g
and &&
s their outputs together.
A function wrapping calls to the two functions in an &&
operation, returning the result of the first
function if it is false-y and the result of the second function otherwise. Note that this is
short-circuited, meaning that the second function will not be invoked if the first returns a false-y
value.
var gt10 = function(x) { return x > 10; };
var even = function(x) { return x % 2 === 0 };
var f = R.both(gt10, even);
f(100); //=> true
f(101); //=> false
call Function
-
function
fn
The function to apply to the remaining arguments.
-
*
args
Any number of positional arguments.
Returns the result of calling its first argument with the remaining
arguments. This is occasionally useful as a converging function for
R.converge
: the left branch can produce a function while the right
branch produces a value to be passed to that function as an argument.
var indentN = R.pipe(R.times(R.always(' ')),
R.join(''),
R.replace(/^(?!$)/gm));
var format = R.converge(R.call,
R.pipe(R.prop('indent'), indentN),
R.prop('value'));
format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n'
chain List
- function fn
- Array list
chain
maps a function over a list and concatenates the results.
This implementation is compatible with the
Fantasy-land Chain spec, and will work with types that implement that spec.
chain
is also known as flatMap
in some libraries
var duplicate = function(n) {
return [n, n];
};
R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]
clone Object
-
*
value
The object or array to clone
A new object or array.
Creates a deep copy of the value which may contain (nested) Array
s and
Object
s, Number
s, String
s, Boolean
s and Date
s. Function
s are
not copied, but assigned by their reference.
var objects = [{}, {}, {}];
var objectsClone = R.clone(objects);
objects[0] === objectsClone[0]; //=> false
commute List
-
function
of
A function that returns the data type to return
-
Array
list
An array of functors of the same type
Turns a list of Functors into a Functor of a list.
R.commute(R.of, [[1], [2, 3]]); //=> [[1, 2], [1, 3]]
R.commute(R.of, [[1, 2], [3]]); //=> [[1, 3], [2, 3]]
R.commute(R.of, [[1], [2], [3]]); //=> [[1, 2, 3]]
R.commute(Maybe.of, [Just(1), Just(2), Just(3)]); //=> Just([1, 2, 3])
R.commute(Maybe.of, [Just(1), Just(2), Nothing()]); //=> Nothing()
commuteMap List
-
function
fn
The transformation function
-
function
of
A function that returns the data type to return
-
Array
list
An array of functors of the same type
Turns a list of Functors into a Functor of a list, applying a mapping function to the elements of the list along the way.
R.commuteMap(R.map(R.add(10)), R.of, [[1], [2, 3]]); //=> [[11, 12], [11, 13]]
R.commuteMap(R.map(R.add(10)), R.of, [[1, 2], [3]]); //=> [[11, 13], [12, 13]]
R.commuteMap(R.map(R.add(10)), R.of, [[1], [2], [3]]); //=> [[11, 12, 13]]
R.commuteMap(R.map(R.add(10)), Maybe.of, [Just(1), Just(2), Just(3)]); //=> Just([11, 12, 13])
R.commuteMap(R.map(R.add(10)), Maybe.of, [Just(1), Just(2), Nothing()]); //=> Nothing()
comparator Function
-
function
pred
A predicate function of arity two.
A Function :: a -> b -> Int that returns -1
if a < b, 1
if b < a, otherwise 0
.
Makes a comparator function out of a function that reports whether the first element is less than the second.
var cmp = R.comparator(function(a, b) {
return a.age < b.age;
});
var people = [
// ...
];
R.sort(cmp, people);
complement Logic
- function f
Takes a function f
and returns a function g
such that:
applying
g
to zero or more arguments will give true if applying the same arguments tof
gives a logical false value; andapplying
g
to zero or more arguments will give false if applying the same arguments tof
gives a logical true value.
var isEven = function(n) { return n % 2 === 0; };
var isOdd = R.complement(isEven);
isOdd(21); //=> true
isOdd(42); //=> false
compose Function
-
function
functions
A variable number of functions.
A new function which represents the result of calling each of the
input functions
, passing the result of each function call to the next, from
right to left.
Creates a new function that runs each of the functions supplied as parameters in turn, passing the return value of each function invocation to the next function invocation, beginning with whatever arguments were passed to the initial invocation.
Note that compose
is a right-associative function, which means the functions provided
will be invoked in order from right to left. In the example var h = compose(f, g)
,
the function h
is equivalent to f( g(x) )
, where x
represents the arguments
originally passed to h
.
var triple = function(x) { return x * 3; };
var double = function(x) { return x * 2; };
var square = function(x) { return x * x; };
var squareThenDoubleThenTriple = R.compose(triple, double, square);
//≅ triple(double(square(5)))
squareThenDoubleThenTriple(5); //=> 150
composeL Function
-
function
lenses
A variable number of lenses.
A new lens which represents the result of calling each of the
input lenses
, passing the result of each getter/setter as the source
to the next, from right to left.
Creates a new lens that allows getting and setting values of nested properties, by following each given lens in succession.
Note that composeL
is a right-associative function, which means the lenses provided
will be invoked in order from right to left.
var headLens = R.lensIndex(0);
var secondLens = R.lensIndex(1);
var xLens = R.lensProp('x');
var secondOfXOfHeadLens = R.composeL(secondLens, xLens, headLens);
var source = [{x: [0, 1], y: [2, 3]}, {x: [4, 5], y: [6, 7]}];
secondOfXOfHeadLens(source); //=> 1
secondOfXOfHeadLens.set(123, source); //=> [{x: [0, 123], y: [2, 3]}, {x: [4, 5], y: [6, 7]}]
composeP Function
-
function
functions
A variable number of functions.
A new function which represents the result of calling each of the
input functions
, passing either the returned result or the asynchronously
resolved value) of each function call to the next, from right to left.
Similar to compose
but with automatic handling of promises (or, more
precisely, "thenables"). The behavior is identical to that of
compose() if all composed functions return something other than
promises (i.e., objects with a .then() method). If one of the function
returns a promise, however, then the next function in the composition
is called asynchronously, in the success callback of the promise, using
the resolved value as an input. Note that composeP
is a right-
associative function, just like compose
.
var Q = require('q');
var triple = function(x) { return x * 3; };
var double = function(x) { return x * 2; };
var squareAsync = function(x) { return Q.when(x * x); };
var squareAsyncThenDoubleThenTriple = R.composeP(triple, double, squareAsync);
//≅ squareAsync(5).then(function(x) { return triple(double(x)) };
squareAsyncThenDoubleThenTriple(5)
.then(function(result) {
// result is 150
});
concat List
-
Array
list1
The first list to merge.
-
Array
list2
The second set to merge.
A new array consisting of the contents of list1
followed by the
contents of list2
. If, instead of an Array for list1
, you pass an
object with a concat
method on it, concat
will call list1.concat
and pass it the value of list2
.
Returns a new list consisting of the elements of the first list followed by the elements of the second.
R.concat([], []); //=> []
R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
R.concat('ABC', 'DEF'); // 'ABCDEF'
cond Logic
- function functions
Returns a function, fn
, which encapsulates if/else-if/else logic.
Each argument to R.cond
is a [predicate, transform] pair. All of
the arguments to fn
are applied to each of the predicates in turn
until one returns a "truthy" value, at which point fn
returns the
result of applying its arguments to the corresponding transformer.
If none of the predicates matches, fn
returns undefined.
var fn = R.cond(
[R.equals(0), R.always('water freezes at 0°C')],
[R.equals(100), R.always('water boils at 100°C')],
[R.T, function(temp) { return 'nothing special happens at ' + temp + '°C'; }]
);
fn(0); //=> 'water freezes at 0°C'
fn(50); //=> 'nothing special happens at 50°C'
fn(100); //=> 'water boils at 100°C'
construct Function
-
function
Fn
The constructor function to wrap.
A wrapped, curried constructor function.
Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type.
// Constructor function
var Widget = function(config) {
// ...
};
Widget.prototype = {
// ...
};
var allConfigs = [
// ...
];
R.map(R.construct(Widget), allConfigs); // a list of Widgets
constructN Function
-
Number
n
The arity of the constructor function.
-
function
Fn
The constructor function to wrap.
A wrapped, curried constructor function.
Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. The arity of the function returned is specified to allow using variadic constructor functions.
// Variadic constructor function
var Widget = function() {
this.children = Array.prototype.slice.call(arguments);
// ...
};
Widget.prototype = {
// ...
};
var allConfigs = [
// ...
];
R.map(R.constructN(1, Widget), allConfigs); // a list of Widgets
contains List
-
Object
a
The item to compare against.
-
Array
list
The array to consider.
true
if the item is in the list, false
otherwise.
Returns true
if the specified value is equal, in R.equals
terms,
to at least one element of the given list; false
otherwise.
R.contains(3, [1, 2, 3]); //=> true
R.contains(4, [1, 2, 3]); //=> false
R.contains([42], [[42]]); //=> true
containsWith List
-
function
pred
A predicate used to test whether two items are equal.
-
*
x
The item to find
-
Array
list
The list to iterate over
true
if x
is in list
, else false
.
Returns true
if the x
is found in the list
, using pred
as an
equality predicate for x
.
var xs = [{x: 12}, {x: 11}, {x: 10}];
R.containsWith(function(a, b) { return a.x === b.x; }, {x: 10}, xs); //=> true
R.containsWith(function(a, b) { return a.x === b.x; }, {x: 1}, xs); //=> false
converge Function
-
function
after
A function.
after
will be invoked with the return values offn1
andfn2
as its arguments. -
function
functions
A variable number of functions.
A new function.
Accepts at least three functions and returns a new function. When invoked, this new
function will invoke the first function, after
, passing as its arguments the
results of invoking the subsequent functions with whatever arguments are passed to
the new function.
var add = function(a, b) { return a + b; };
var multiply = function(a, b) { return a * b; };
var subtract = function(a, b) { return a - b; };
//≅ multiply( add(1, 2), subtract(1, 2) );
R.converge(multiply, add, subtract)(1, 2); //=> -3
var add3 = function(a, b, c) { return a + b + c; };
R.converge(add3, multiply, add, subtract)(1, 2); //=> 4
countBy Relation
-
function
fn
The function used to map values to keys.
-
Array
list
The list to count elements from.
An object mapping keys to number of occurrences in the list.
Counts the elements of a list according to how many match each value
of a key generated by the supplied function. Returns an object
mapping the keys produced by fn
to the number of occurrences in
the list. Note that all keys are coerced to strings because of how
JavaScript objects work.
var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2];
var letters = R.split('', 'abcABCaaaBBc');
R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1}
R.countBy(R.toLower)(letters); //=> {'a': 5, 'b': 4, 'c': 3}
createMapEntry Object
- String key
- * val
Creates an object containing a single key:value pair.
var matchPhrases = R.compose(
R.createMapEntry('must'),
R.map(R.createMapEntry('match_phrase'))
);
matchPhrases(['foo', 'bar', 'baz']); //=> {must: [{match_phrase: 'foo'}, {match_phrase: 'bar'}, {match_phrase: 'baz'}]}
curry Function
-
function
fn
The function to curry.
A new, curried function.
Returns a curried equivalent of the provided function. The curried
function has two unusual capabilities. First, its arguments needn't
be provided one at a time. If f
is a ternary function and g
is
R.curry(f)
, the following are equivalent:
g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
Secondly, the special placeholder value R.__
may be used to specify
"gaps", allowing partial application of any combination of arguments,
regardless of their positions. If g
is as above and _
is R.__
,
the following are equivalent:
g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
g(_, 2)(_, 3)(1)
var addFourNumbers = function(a, b, c, d) {
return a + b + c + d;
};
var curriedAddFourNumbers = R.curry(addFourNumbers);
var f = curriedAddFourNumbers(1, 2);
var g = f(3);
g(4); //=> 10
curryN Function
-
Number
length
The arity for the returned function.
-
function
fn
The function to curry.
A new, curried function.
Returns a curried equivalent of the provided function, with the
specified arity. The curried function has two unusual capabilities.
First, its arguments needn't be provided one at a time. If g
is
R.curryN(3, f)
, the following are equivalent:
g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
Secondly, the special placeholder value R.__
may be used to specify
"gaps", allowing partial application of any combination of arguments,
regardless of their positions. If g
is as above and _
is R.__
,
the following are equivalent:
g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
g(_, 2)(_, 3)(1)
var addFourNumbers = function() {
return R.sum([].slice.call(arguments, 0, 4));
};
var curriedAddFourNumbers = R.curryN(4, addFourNumbers);
var f = curriedAddFourNumbers(1, 2);
var g = f(3);
g(4); //=> 10
dec Math
- Number n
Decrements its argument.
R.dec(42); //=> 41
defaultTo Logic
-
a
val
The default value.
-
b
val
The value to return if it is not null or undefined
The the second value or the default value
Returns the second argument if it is not null or undefined. If it is null or undefined, the first (default) argument is returned.
var defaultTo42 = R.defaultTo(42);
defaultTo42(null); //=> 42
defaultTo42(undefined); //=> 42
defaultTo42('Ramda'); //=> 'Ramda'
difference Relation
-
Array
list1
The first list.
-
Array
list2
The second list.
The elements in list1
that are not in list2
.
Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2]
R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5]
differenceWith Relation
-
function
pred
A predicate used to test whether two items are equal.
-
Array
list1
The first list.
-
Array
list2
The second list.
The elements in list1
that are not in list2
.
Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. Duplication is determined according to the value returned by applying the supplied predicate to two list elements.
function cmp(x, y) { return x.a === y.a; }
var l1 = [{a: 1}, {a: 2}, {a: 3}];
var l2 = [{a: 3}, {a: 4}];
R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}]
dissoc Object
-
String
prop
the name of the property to dissociate
-
Object
obj
the object to clone
a new object similar to the original but without the specified property
Returns a new object that does not contain a prop
property.
R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3}
dissocPath Object
-
Array
path
the path to set
-
Object
obj
the object to clone
a new object without the property at path
Makes a shallow clone of an object, omitting the property at the given path. Note that this copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference.
R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}}
divide Math
-
Number
a
The first value.
-
Number
b
The second value.
The result of a / b
.
Divides two numbers. Equivalent to a / b
.
R.divide(71, 100); //=> 0.71
var half = R.divide(R.__, 2);
half(42); //=> 21
var reciprocal = R.divide(1);
reciprocal(4); //=> 0.25
drop List
-
Number
n
The number of elements of
xs
to skip. -
Array
xs
The collection to consider.
Returns a list containing all but the first n
elements of the given list
.
Acts as a transducer if a transformer is given in list position.
R.drop(1, ['foo', 'bar', 'baz']); //=> ['bar', 'baz']
R.drop(2, ['foo', 'bar', 'baz']); //=> ['baz']
R.drop(3, ['foo', 'bar', 'baz']); //=> []
R.drop(4, ['foo', 'bar', 'baz']); //=> []
R.drop(3, 'ramda'); //=> 'da'
dropRepeats List
-
Array
list
The array to consider.
list
without repeating elements.
Returns a new list without any consecutively repeating elements.
R.equals
is used to determine equality.
Acts as a transducer if a transformer is given in list position.
R.dropRepeats([1, 1, 1, 2, 3, 4, 4, 2, 2]); //=> [1, 2, 3, 4, 2]
dropRepeatsWith List
-
function
pred
A predicate used to test whether two items are equal.
-
Array
list
The array to consider.
list
without repeating elements.
Returns a new list without any consecutively repeating elements. Equality is determined by applying the supplied predicate two consecutive elements. The first element in a series of equal element is the one being preserved.
Acts as a transducer if a transformer is given in list position.
function lengthEq(x, y) { return Math.abs(x) === Math.abs(y); };
var l = [1, -1, 1, 3, 4, -4, -4, -5, 5, 3, 3];
R.dropRepeatsWith(lengthEq, l); //=> [1, 3, 4, -5, 3]
dropWhile List
-
function
fn
The function called per iteration.
-
Array
list
The collection to iterate over.
A new array.
Returns a new list containing the last n
elements of a given list, passing each value
to the supplied predicate function, skipping elements while the predicate function returns
true
. The predicate function is passed one argument: (value).
Acts as a transducer if a transformer is given in list position.
var lteTwo = function(x) {
return x <= 2;
};
R.dropWhile(lteTwo, [1, 2, 3, 4, 3, 2, 1]); //=> [3, 4, 3, 2, 1]
either Logic
-
function
f
a predicate
-
function
g
another predicate
a function that applies its arguments to f
and g
and ||
s their outputs together.
A function wrapping calls to the two functions in an ||
operation, returning the result of the first
function if it is truth-y and the result of the second function otherwise. Note that this is
short-circuited, meaning that the second function will not be invoked if the first returns a truth-y
value.
var gt10 = function(x) { return x > 10; };
var even = function(x) { return x % 2 === 0 };
var f = R.either(gt10, even);
f(101); //=> true
f(8); //=> true
empty Function
An empty array.
empty
returns an empty list for any argument, except when the argument satisfies the
Fantasy-land Monoid spec. In that case, this function will return the result of invoking
empty
on that Monoid.
R.empty([1,2,3,4,5]); //=> []
eq Relation
- * a
- * b
Tests if two items are equal. Equality is strict here, meaning reference equality for objects and non-coercing equality for primitives.
Has Object.is
semantics: NaN
is considered equal to NaN
; 0
and -0
are not considered equal.
var o = {};
R.eq(o, o); //=> true
R.eq(o, {}); //=> false
R.eq(1, 1); //=> true
R.eq(1, '1'); //=> false
R.eq(0, -0); //=> false
R.eq(NaN, NaN); //=> true
eqDeep Relation
- * a
- * b
Performs a deep test on whether two items are equal. Equality implies the two items are semmatically equivalent. Cyclic structures are handled as expected
var o = {};
R.eqDeep(o, o); //=> true
R.eqDeep(o, {}); //=> true
R.eqDeep(1, 1); //=> true
R.eqDeep(1, '1'); //=> false
var a = {}; a.v = a;
var b = {}; b.v = b;
R.eqDeep(a, b); //=> true
eqProps Object
-
String
prop
The name of the property to compare
- Object obj1
- Object obj2
Reports whether two objects have the same value, in R.equals
terms,
for the specified property. Useful as a curried predicate.
var o1 = { a: 1, b: 2, c: 3, d: 4 };
var o2 = { a: 10, b: 20, c: 3, d: 40 };
R.eqProps('a', o1, o2); //=> false
R.eqProps('c', o1, o2); //=> true
equals Relation
- * a
- * b
Returns true
if its arguments are equivalent, false
otherwise.
Dispatches to an equals
method if present. Handles cyclical data
structures.
R.equals(1, 1); //=> true
R.equals(1, '1'); //=> false
R.equals([1, 2, 3], [1, 2, 3]); //=> true
var a = {}; a.v = a;
var b = {}; b.v = b;
R.equals(a, b); //=> true
evolve Object
-
Object
transformations
The object specifying transformation functions to apply to the object.
-
Object
object
The object to be transformed.
The transformed object.
Creates a new object by recursively evolving a shallow copy of object
, according to the
transformation
functions. All non-primitive properties are copied by reference.
A tranformation
function will not be invoked if its corresponding key does not exist in
the evolved object.
var tomato = {firstName: ' Tomato ', elapsed: 100, remaining: 1400};
var transformations = {
firstName: R.trim,
lastName: R.trim, // Will not get invoked.
data: {elapsed: R.add(1), remaining: R.add(-1)}
};
R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}}
F Function
false
A function that always returns false
. Any passed in parameters are ignored.
R.F(); //=> false
filter List
-
function
fn
The function called per iteration.
-
Array
list
The collection to iterate over.
The new filtered array.
Returns a new list containing only those items that match a given predicate function. The predicate function is passed one argument: (value).
Note that R.filter
does not skip deleted or unassigned indices, unlike the native
Array.prototype.filter
method. For more details on this behavior, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Description
Acts as a transducer if a transformer is given in list position.
var isEven = function(n) {
return n % 2 === 0;
};
R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4]
filterIndexed List
-
function
fn
The function called per iteration.
-
Array
list
The collection to iterate over.
The new filtered array.
Like filter
, but passes additional parameters to the predicate function. The predicate
function is passed three arguments: (value, index, list).
var lastTwo = function(val, idx, list) {
return list.length - idx <= 2;
};
R.filterIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9]
find List
-
function
fn
The predicate function used to determine if the element is the desired one.
-
Array
list
The array to consider.
The element found, or undefined
.
Returns the first element of the list which matches the predicate, or undefined
if no
element matches.
Acts as a transducer if a transformer is given in list position.
var xs = [{a: 1}, {a: 2}, {a: 3}];
R.find(R.propEq('a', 2))(xs); //=> {a: 2}
R.find(R.propEq('a', 4))(xs); //=> undefined
findIndex List
-
function
fn
The predicate function used to determine if the element is the desired one.
-
Array
list
The array to consider.
The index of the element found, or -1
.
Returns the index of the first element of the list which matches the predicate, or -1
if no element matches.
Acts as a transducer if a transformer is given in list position.
var xs = [{a: 1}, {a: 2}, {a: 3}];
R.findIndex(R.propEq('a', 2))(xs); //=> 1
R.findIndex(R.propEq('a', 4))(xs); //=> -1
findLast List
-
function
fn
The predicate function used to determine if the element is the desired one.
-
Array
list
The array to consider.
The element found, or undefined
.
Returns the last element of the list which matches the predicate, or undefined
if no
element matches.
Acts as a transducer if a transformer is given in list position.
var xs = [{a: 1, b: 0}, {a:1, b: 1}];
R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1}
R.findLast(R.propEq('a', 4))(xs); //=> undefined
findLastIndex List
-
function
fn
The predicate function used to determine if the element is the desired one.
-
Array
list
The array to consider.
The index of the element found, or -1
.
Returns the index of the last element of the list which matches the predicate, or
-1
if no element matches.
Acts as a transducer if a transformer is given in list position.
var xs = [{a: 1, b: 0}, {a:1, b: 1}];
R.findLastIndex(R.propEq('a', 1))(xs); //=> 1
R.findLastIndex(R.propEq('a', 4))(xs); //=> -1
flatten List
-
Array
list
The array to consider.
The flattened list.
Returns a new list by pulling every item out of it (and all its sub-arrays) and putting them in a new array, depth-first.
R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]);
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
flip Function
-
function
fn
The function to invoke with its first two parameters reversed.
The result of invoking fn
with its first two parameters' order reversed.
Returns a new function much like the supplied one, except that the first two arguments' order is reversed.
var mergeThree = function(a, b, c) {
return ([]).concat(a, b, c);
};
mergeThree(1, 2, 3); //=> [1, 2, 3]
R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3]
forEach List
-
function
fn
The function to invoke. Receives one argument,
value
. -
Array
list
The list to iterate over.
The original list.
Iterate over an input list
, calling a provided function fn
for each element in the
list.
fn
receives one argument: (value).
Note: R.forEach
does not skip deleted or unassigned indices (sparse arrays), unlike
the native Array.prototype.forEach
method. For more details on this behavior, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
Also note that, unlike Array.prototype.forEach
, Ramda's forEach
returns the original
array. In some libraries this function is named each
.
var printXPlusFive = function(x) { console.log(x + 5); };
R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3]
//-> 6
//-> 7
//-> 8
forEachIndexed List
-
function
fn
The function to invoke. Receives three arguments: (
value
,index
,list
). -
Array
list
The list to iterate over.
The original list.
Like forEach
, but passes additional parameters to the predicate function.
fn
receives three arguments: (value, index, list).
Note: R.forEachIndexed
does not skip deleted or unassigned indices (sparse arrays),
unlike the native Array.prototype.forEach
method. For more details on this behavior,
see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
Also note that, unlike Array.prototype.forEach
, Ramda's forEach
returns the original
array. In some libraries this function is named each
.
// Note that having access to the original `list` allows for
// mutation. While you *can* do this, it's very un-functional behavior:
var plusFive = function(num, idx, list) { list[idx] = num + 5 };
R.forEachIndexed(plusFive, [1, 2, 3]); //=> [6, 7, 8]
fromPairs List
-
Array
pairs
An array of two-element arrays that will be the keys and values of the output object.
The object made by pairing up keys
and values
.
Creates a new object out of a list key-value pairs.
R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3}
functions Object
-
Object
obj
The objects with functions in it
A list of the object's own properties that map to functions.
Returns a list of function names of object's own functions
R.functions(R); // returns list of ramda's own function names
var F = function() { this.x = function(){}; this.y = 1; }
F.prototype.z = function() {};
F.prototype.a = 100;
R.functions(new F()); //=> ["x"]
functionsIn Object
-
Object
obj
The objects with functions in it
A list of the object's own properties and prototype properties that map to functions.
Returns a list of function names of object's own and prototype functions
R.functionsIn(R); // returns list of ramda's own and prototype function names
var F = function() { this.x = function(){}; this.y = 1; }
F.prototype.z = function() {};
F.prototype.a = 100;
R.functionsIn(new F()); //=> ["x", "z"]
groupBy List
-
function
fn
Function :: a -> String
-
Array
list
The array to group
An object with the output of fn
for keys, mapped to arrays of elements
that produced that key when passed to fn
.
Splits a list into sub-lists stored in an object, based on the result of calling a String-returning function on each element, and grouping the results according to values returned.
Acts as a transducer if a transformer is given in list position.
var byGrade = R.groupBy(function(student) {
var score = student.score;
return score < 65 ? 'F' :
score < 70 ? 'D' :
score < 80 ? 'C' :
score < 90 ? 'B' : 'A';
});
var students = [{name: 'Abby', score: 84},
{name: 'Eddy', score: 58},
// ...
{name: 'Jack', score: 69}];
byGrade(students);
// {
// 'A': [{name: 'Dianne', score: 99}],
// 'B': [{name: 'Abby', score: 84}]
// // ...,
// 'F': [{name: 'Eddy', score: 58}]
// }
gt Math
- Number a
- Number b
a > b
Returns true if the first parameter is greater than the second.
R.gt(2, 6); //=> false
R.gt(2, 0); //=> true
R.gt(2, 2); //=> false
R.gt(R.__, 2)(10); //=> true
R.gt(2)(10); //=> false
gte Math
- Number a
- Number b
a >= b
Returns true if the first parameter is greater than or equal to the second.
R.gte(2, 6); //=> false
R.gte(2, 0); //=> true
R.gte(2, 2); //=> true
R.gte(R.__, 6)(2); //=> false
R.gte(2)(0); //=> true
has Object
-
String
prop
The name of the property to check for.
-
Object
obj
The object to query.
Whether the property exists.
Returns whether or not an object has an own property with the specified name
var hasName = R.has('name');
hasName({name: 'alice'}); //=> true
hasName({name: 'bob'}); //=> true
hasName({}); //=> false
var point = {x: 0, y: 0};
var pointHas = R.has(R.__, point);
pointHas('x'); //=> true
pointHas('y'); //=> true
pointHas('z'); //=> false
hasIn Object
-
String
prop
The name of the property to check for.
-
Object
obj
The object to query.
Whether the property exists.
Returns whether or not an object or its prototype chain has a property with the specified name
function Rectangle(width, height) {
this.width = width;
this.height = height;
}
Rectangle.prototype.area = function() {
return this.width * this.height;
};
var square = new Rectangle(2, 2);
R.hasIn('width', square); //=> true
R.hasIn('area', square); //=> true
head List
-
Array
list
The array to consider.
The first element of the list, or undefined
if the list is empty.
Returns the first element in a list.
In some libraries this function is named first
.
R.head(['fi', 'fo', 'fum']); //=> 'fi'
identical Relation
- * a
- * b
Returns true if its arguments are identical, false otherwise. Values are
identical if they reference the same memory. NaN
is identical to NaN
;
0
and -0
are not identical.
var o = {};
R.identical(o, o); //=> true
R.identical(1, 1); //=> true
R.identical(1, '1'); //=> false
R.identical([], []); //=> false
R.identical(0, -0); //=> false
R.identical(NaN, NaN); //=> true
identity Function
-
*
x
The value to return.
The input value, x
.
A function that does nothing but return the parameter supplied to it. Good as a default or placeholder function.
R.identity(1); //=> 1
var obj = {};
R.identity(obj) === obj; //=> true
ifElse Logic
-
function
condition
A predicate function
-
function
onTrue
A function to invoke when the
condition
evaluates to a truthy value. -
function
onFalse
A function to invoke when the
condition
evaluates to a falsy value.
A new unary function that will process either the onTrue
or the onFalse
function depending upon the result of the condition
predicate.
Creates a function that will process either the onTrue
or the onFalse
function depending
upon the result of the condition
predicate.
// Flatten all arrays in the list but leave other values alone.
var flattenArrays = R.map(R.ifElse(Array.isArray, R.flatten, R.identity));
flattenArrays([[0], [[10], [8]], 1234, {}]); //=> [[0], [10, 8], 1234, {}]
flattenArrays([[[10], 123], [8, [10]], "hello"]); //=> [[10, 123], [8, 10], "hello"]
inc Math
- Number n
Increments its argument.
R.inc(42); //=> 43
indexOf List
-
*
target
The item to find.
-
Array
xs
The array to search in.
the index of the target, or -1 if the target is not found.
Returns the position of the first occurrence of an item in an array,
or -1 if the item is not included in the array. R.equals
is used to
determine equality.
R.indexOf(3, [1,2,3,4]); //=> 2
R.indexOf(10, [1,2,3,4]); //=> -1
init List
-
Array
list
The array to consider.
A new array containing all but the last element of the input list, or an empty list if the input list is empty.
Returns all but the last element of a list.
R.init(['fi', 'fo', 'fum']); //=> ['fi', 'fo']
insert List
-
Number
index
The position to insert the element
-
*
elt
The element to insert into the Array
-
Array
list
The list to insert into
A new Array with elt
inserted at index
.
Inserts the supplied element into the list, at index index
. Note
that this is not destructive: it returns a copy of the list with the changes.
No lists have been harmed in the application of this function.
R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4]
insertAll List
-
Number
index
The position to insert the sub-list
-
Array
elts
The sub-list to insert into the Array
-
Array
list
The list to insert the sub-list into
A new Array with elts
inserted starting at index
.
Inserts the sub-list into the list, at index index
. Note that this
is not destructive: it returns a copy of the list with the changes.
No lists have been harmed in the application of this function.
R.insertAll(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4]
intersection Relation
-
Array
list1
The first list.
-
Array
list2
The second list.
The list of elements found in both list1
and list2
.
Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists.
R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3]
intersectionWith Relation
-
function
pred
A predicate function that determines whether the two supplied elements are equal.
-
Array
list1
One list of items to compare
-
Array
list2
A second list of items to compare
A new list containing those elements common to both lists.
Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists. Duplication is determined according to the value returned by applying the supplied predicate to two list elements.
var buffaloSpringfield = [
{id: 824, name: 'Richie Furay'},
{id: 956, name: 'Dewey Martin'},
{id: 313, name: 'Bruce Palmer'},
{id: 456, name: 'Stephen Stills'},
{id: 177, name: 'Neil Young'}
];
var csny = [
{id: 204, name: 'David Crosby'},
{id: 456, name: 'Stephen Stills'},
{id: 539, name: 'Graham Nash'},
{id: 177, name: 'Neil Young'}
];
var sameId = function(o1, o2) {return o1.id === o2.id;};
R.intersectionWith(sameId, buffaloSpringfield, csny);
//=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}]
intersperse List
-
*
separator
The element to add to the list.
-
Array
list
The list to be interposed.
The new list.
Creates a new list with the separator interposed between elements.
R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a']
into List
-
*
acc
The initial accumulator value.
-
function
xf
The transducer function. Receives a transformer and returns a transformer.
-
Array
list
The list to iterate over.
The final, accumulated value.
Transforms the items of the list with the transducer and appends the transformed items to the accumulator using an appropriate iterator function based on the accumulator type.
The accumulator can be an array, string, object or a transformer. Iterated items will be appended to arrays and concatenated to strings. Objects will be merged directly or 2-item arrays will be merged as key, value pairs.
The accumulator can also be a transformer object that provides a 2-arity reducing iterator function, step, 0-arity initial value function, init, and 1-arity result extraction function result. The step function is used as the iterator function in reduce. The result function is used to convert the final accumulator into the return type and in most cases is R.identity. The init function is used to provide the initial accumulator.
The iteration is performed with R.reduce after initializing the transducer.
var numbers = [1, 2, 3, 4];
var transducer = R.compose(R.map(R.add(1)), R.take(2));
R.into([], transducer, numbers); //=> [2, 3]
var intoArray = R.into([]);
intoArray(transducer, numbers); //=> [2, 3]
invert Object
-
Object
obj
The object or array to invert
out A new object with keys in an array.
Same as R.invertObj, however this accounts for objects with duplicate values by putting the values into an array.
var raceResultsByFirstName = {
first: 'alice',
second: 'jake',
third: 'alice',
};
R.invert(raceResultsByFirstName);
//=> { 'alice': ['first', 'third'], 'jake':['second'] }
invertObj Object
-
Object
obj
The object or array to invert
out A new object
Returns a new object with the keys of the given object as values, and the values of the given object as keys.
var raceResults = {
first: 'alice',
second: 'jake'
};
R.invertObj(raceResults);
//=> { 'alice': 'first', 'jake':'second' }
// Alternatively:
var raceResults = ['alice', 'jake'];
R.invertObj(raceResults);
//=> { 'alice': '0', 'jake':'1' }
invoke Object
- String methodName
- Array args
- Object obj
Returns the result of applying obj[methodName]
to args
.
// toBinary :: Number -> String
var toBinary = R.invoke('toString', [2])
toBinary(42); //=> '101010'
toBinary(63); //=> '111111'
invoker Function
-
Number
arity
Number of arguments the returned function should take before the target object.
-
function
method
Name of the method to call.
A new curried function.
Turns a named method with a specified arity into a function that can be called directly supplied with arguments and a target object.
The returned function is curried and accepts arity + 1
parameters where
the final parameter is the target object.
var sliceFrom = R.invoker(1, 'slice');
sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm'
var sliceFrom6 = R.invoker(2, 'slice')(6);
sliceFrom6(8, 'abcdefghijklm'); //=> 'gh'
is Type
-
Object
ctor
A constructor
-
*
val
The value to test
See if an object (val
) is an instance of the supplied constructor.
This function will check up the inheritance chain, if any.
R.is(Object, {}); //=> true
R.is(Number, 1); //=> true
R.is(Object, 1); //=> false
R.is(String, 's'); //=> true
R.is(String, new String('')); //=> true
R.is(Object, new String('')); //=> true
R.is(Object, 's'); //=> false
R.is(Number, {}); //=> false
isArrayLike Type
-
*
x
The object to test.
true
if x
has a numeric length property and extreme indices defined; false
otherwise.
Tests whether or not an object is similar to an array.
R.isArrayLike([]); //=> true
R.isArrayLike(true); //=> false
R.isArrayLike({}); //=> false
R.isArrayLike({length: 10}); //=> false
R.isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true
isEmpty Logic
- Array list
Reports whether the list has zero elements.
R.isEmpty([1, 2, 3]); //=> false
R.isEmpty([]); //=> true
R.isEmpty(''); //=> true
R.isEmpty(null); //=> false
R.isEmpty(R.keys({})); //=> true
R.isEmpty({}); //=> false ({} does not have a length property)
R.isEmpty({length: 0}); //=> true
isNil Type
-
*
x
The value to test.
true
if x
is undefined
or null
, otherwise false
.
Checks if the input value is null
or undefined
.
R.isNil(null); //=> true
R.isNil(undefined); //=> true
R.isNil(0); //=> false
R.isNil([]); //=> false
isSet List
-
Array
list
The array to consider.
true
if all elements are unique, else false
.
Returns true
if all elements are unique, in R.equals
terms,
otherwise false
.
R.isSet(['1', 1]); //=> true
R.isSet([1, 1]); //=> false
R.isSet([[42], [42]]); //=> false
join List
-
Number
separator
The string used to separate the elements.
-
Array
xs
The elements to join into a string.
str The string made by concatenating xs
with separator
.
Returns a string made by inserting the separator
between each
element and concatenating all the elements into a single string.
var spacer = R.join(' ');
spacer(['a', 2, 3.4]); //=> 'a 2 3.4'
R.join('|', [1, 2, 3]); //=> '1|2|3'
keys Object
-
Object
obj
The object to extract properties from
An array of the object's own properties.
Returns a list containing the names of all the enumerable own properties of the supplied object. Note that the order of the output array is not guaranteed to be consistent across different JS platforms.
R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
keysIn Object
-
Object
obj
The object to extract properties from
An array of the object's own and prototype properties.
Returns a list containing the names of all the properties of the supplied object, including prototype properties. Note that the order of the output array is not guaranteed to be consistent across different JS platforms.
var F = function() { this.x = 'X'; };
F.prototype.y = 'Y';
var f = new F();
R.keysIn(f); //=> ['x', 'y']
last List
-
Array
list
The array to consider.
The last element of the list, or undefined
if the list is empty.
Returns the last element from a list.
R.last(['fi', 'fo', 'fum']); //=> 'fum'
lastIndexOf List
-
*
target
The item to find.
-
Array
xs
The array to search in.
the index of the target, or -1 if the target is not found.
Returns the position of the last occurrence of an item in
an array, or -1 if the item is not included in the array.
R.equals
is used to determine equality.
R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6
R.lastIndexOf(10, [1,2,3,4]); //=> -1
length List
-
Array
list
The array to inspect.
The length of the array.
Returns the number of elements in the array by returning list.length
.
R.length([]); //=> 0
R.length([1, 2, 3]); //=> 3
lens Object
-
function
get
A function that gets a value by property name
-
function
set
A function that sets a value by property name
the returned function has set
and map
properties that are
also curried functions.
Creates a lens. Supply a function to get
values from inside an object, and a set
function to change values on an object. (n.b.: This can, and should, be done without
mutating the original object!) The lens is a function wrapped around the input get
function, with the set
function attached as a property on the wrapper. A map
function is also attached to the returned function that takes a function to operate
on the specified (get
) property, which is then set
before returning. The attached
set
and map
functions are curried.
var headLens = R.lens(
function get(arr) { return arr[0]; },
function set(val, arr) { return [val].concat(arr.slice(1)); }
);
headLens([10, 20, 30, 40]); //=> 10
headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40]
headLens.map(function(x) { return x + 1; }, [10, 20, 30, 40]); //=> [11, 20, 30, 40]
var phraseLens = R.lens(
function get(obj) { return obj.phrase; },
function set(val, obj) {
var out = R.clone(obj);
out.phrase = val;
return out;
}
);
var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'};
var obj2 = { phrase: "What's all this, then?"};
phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!'
phraseLens(obj2); // => "What's all this, then?"
phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'}
phraseLens.map(R.toUpper, obj2); //=> { phrase: "WHAT'S ALL THIS, THEN?"}
lensIndex List
-
Number
n
The index of the array that the returned lens will focus on.
the returned function has set
and map
properties that are
also curried functions.
Creates a lens that will focus on index n
of the source array.
var headLens = R.lensIndex(0);
headLens([10, 20, 30, 40]); //=> 10
headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40]
headLens.map(function(x) { return x + 1; }, [10, 20, 30, 40]); //=> [11, 20, 30, 40]
lensOn Object
-
function
get
A function that gets a value by property name
-
function
set
A function that sets a value by property name
-
Object
the
actual object of interest
the returned function has set
and map
properties that are
also curried functions.
Returns a lens associated with the provided object.
var xo = {x: 1};
var xoLens = R.lensOn(function get(o) { return o.x; },
function set(v) { return {x: v}; },
xo);
xoLens(); //=> 1
xoLens.set(1000); //=> {x: 1000}
xoLens.map(R.add(1)); //=> {x: 2}
lensProp Object
-
String
k
A string that represents a property to focus on.
the returned function has set
and map
properties that are
also curried functions.
Creates a lens that will focus on property k
of the source object.
var phraseLens = R.lensProp('phrase');
var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'};
var obj2 = { phrase: "What's all this, then?"};
phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!'
phraseLens(obj2); // => "What's all this, then?"
phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'}
phraseLens.map(R.toUpper, obj2); //=> { phrase: "WHAT'S ALL THIS, THEN?"}
lift Function
-
function
fn
The function to lift into higher context
The function fn
applicable to mappable objects.
"lifts" a function of arity > 1 so that it may "map over" an Array or other Functor.
var madd3 = R.lift(R.curry(function(a, b, c) {
return a + b + c;
}));
madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
var madd5 = R.lift(R.curry(function(a, b, c, d, e) {
return a + b + c + d + e;
}));
madd5([1,2], [3], [4, 5], [6], [7, 8]); //=> [21, 22, 22, 23, 22, 23, 23, 24]
liftN Function
-
function
fn
The function to lift into higher context
The function fn
applicable to mappable objects.
"lifts" a function to be the specified arity, so that it may "map over" that many lists (or other Functors).
var madd3 = R.liftN(3, R.curryN(3, function() {
return R.reduce(R.add, 0, arguments);
}));
madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
lt Math
- Number a
- Number b
a < b
Returns true if the first parameter is less than the second.
R.lt(2, 6); //=> true
R.lt(2, 0); //=> false
R.lt(2, 2); //=> false
R.lt(5)(10); //=> true
R.lt(R.__, 5)(10); //=> false // right-sectioned currying
lte Math
- Number a
- Number b
a <= b
Returns true if the first parameter is less than or equal to the second.
R.lte(2, 6); //=> true
R.lte(2, 0); //=> false
R.lte(2, 2); //=> true
R.lte(R.__, 2)(1); //=> true
R.lte(2)(10); //=> true
map List
-
function
fn
The function to be called on every element of the input
list
. -
Array
list
The list to be iterated over.
The new list.
Returns a new list, constructed by applying the supplied function to every element of the supplied list.
Note: R.map
does not skip deleted or unassigned indices (sparse arrays), unlike the
native Array.prototype.map
method. For more details on this behavior, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description
Acts as a transducer if a transformer is given in list position.
var double = function(x) {
return x * 2;
};
R.map(double, [1, 2, 3]); //=> [2, 4, 6]
mapAccum List
-
function
fn
The function to be called on every element of the input
list
. -
*
acc
The accumulator value.
-
Array
list
The list to iterate over.
The final, accumulated value.
The mapAccum function behaves like a combination of map and reduce; it applies a function to each element of a list, passing an accumulating parameter from left to right, and returning a final value of this accumulator together with the new list.
The iterator function receives two arguments, acc and value, and should return a tuple [acc, value].
var digits = ['1', '2', '3', '4'];
var append = function(a, b) {
return [a + b, a + b];
}
R.mapAccum(append, 0, digits); //=> ['01234', ['01', '012', '0123', '01234']]
mapAccumRight List
-
function
fn
The function to be called on every element of the input
list
. -
*
acc
The accumulator value.
-
Array
list
The list to iterate over.
The final, accumulated value.
The mapAccumRight function behaves like a combination of map and reduce; it applies a function to each element of a list, passing an accumulating parameter from right to left, and returning a final value of this accumulator together with the new list.
Similar to mapAccum
, except moves through the input list from the right to the
left.
The iterator function receives two arguments, acc and value, and should return a tuple [acc, value].
var digits = ['1', '2', '3', '4'];
var append = function(a, b) {
return [a + b, a + b];
}
R.mapAccumRight(append, 0, digits); //=> ['04321', ['04321', '0432', '043', '04']]
mapIndexed List
-
function
fn
The function to be called on every element of the input
list
. -
Array
list
The list to be iterated over.
The new list.
Like map
, but passes additional parameters to the mapping function.
fn
receives three arguments: (value, index, list).
Note: R.mapIndexed
does not skip deleted or unassigned indices (sparse arrays), unlike
the native Array.prototype.map
method. For more details on this behavior, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description
var squareEnds = function(elt, idx, list) {
if (idx === 0 || idx === list.length - 1) {
return elt * elt;
}
return elt;
};
R.mapIndexed(squareEnds, [8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81]
mapObj Object
-
function
fn
A function called for each property in
obj
. Its return value will become a new property on the return object. -
Object
obj
The object to iterate over.
A new object with the same keys as obj
and values that are the result
of running each property through fn
.
Map, but for objects. Creates an object with the same keys as obj
and values
generated by running each property of obj
through fn
. fn
is passed one argument:
(value).
var values = { x: 1, y: 2, z: 3 };
var double = function(num) {
return num * 2;
};
R.mapObj(double, values); //=> { x: 2, y: 4, z: 6 }
mapObjIndexed Object
-
function
fn
A function called for each property in
obj
. Its return value will become a new property on the return object. -
Object
obj
The object to iterate over.
A new object with the same keys as obj
and values that are the result
of running each property through fn
.
Like mapObj
, but passes additional arguments to the predicate function. The
predicate function is passed three arguments: (value, key, obj).
var values = { x: 1, y: 2, z: 3 };
var prependKeyAndDouble = function(num, key, obj) {
return key + (num * 2);
};
R.mapObjIndexed(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' }
match String
-
RegExp
rx
A regular expression.
-
String
str
The string to match against
The list of matches, or null if no matches found.
Tests a regular expression against a String
R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na']
mathMod Math
-
Number
m
The dividend.
-
Number
p
the modulus.
The result of b mod a
.
mathMod behaves like the modulo operator should mathematically, unlike the %
operator (and by extension, R.modulo). So while "-17 % 5" is -2,
mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN
when the modulus is zero or negative.
R.mathMod(-17, 5); //=> 3
R.mathMod(17, 5); //=> 2
R.mathMod(17, -5); //=> NaN
R.mathMod(17, 0); //=> NaN
R.mathMod(17.2, 5); //=> NaN
R.mathMod(17, 5.3); //=> NaN
var clock = R.mathMod(R.__, 12);
clock(15); //=> 3
clock(24); //=> 0
var seventeenMod = R.mathMod(17);
seventeenMod(3); //=> 2
seventeenMod(4); //=> 1
seventeenMod(10); //=> 7
max Math
-
Array
list
A list of numbers
The greatest number in the list.
Determines the largest of a list of numbers (or elements that can be cast to numbers)
R.max([7, 3, 9, 2, 4, 9, 3]); //=> 9
maxBy Math
-
function
keyFn
A comparator function for elements in the list
-
Array
list
A list of comparable elements
The greatest element in the list. undefined
if the list is empty.
Determines the largest of a list of items as determined by pairwise comparisons from the supplied comparator. Note that this will return undefined if supplied an empty list.
function cmp(obj) { return obj.x; }
var a = {x: 1}, b = {x: 2}, c = {x: 3};
R.maxBy(cmp, [a, b, c]); //=> {x: 3}
mean Math
- Array list
Returns the mean of the given list of numbers.
R.mean([2, 7, 9]); //=> 6
R.mean([]); //=> NaN
median Math
- Array list
Returns the median of the given list of numbers.
R.median([2, 9, 7]); //=> 7
R.median([7, 2, 10, 9]); //=> 8
R.median([]); //=> NaN
memoize Function
-
function
fn
The function to memoize.
Memoized version of fn
.
Creates a new function that, when invoked, caches the result of calling fn
for a given
argument set and returns the result. Subsequent calls to the memoized fn
with the same
argument set will not result in an additional call to fn
; instead, the cached result
for that set of arguments will be returned.
var count = 0;
var factorial = R.memoize(function(n) {
count += 1;
return R.product(R.range(1, n + 1));
});
factorial(5); //=> 120
factorial(5); //=> 120
factorial(5); //=> 120
count; //=> 1
merge Object
-
Object
a
source object
-
Object
b
object with higher precedence in output
The destination object.
Create a new object with the own properties of a
merged with the own properties of object b
.
This function will not mutate passed-in objects.
R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 });
//=> { 'name': 'fred', 'age': 40 }
var resetToDefault = R.merge(R.__, {x: 0});
resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2}
mergeAll List
-
Array
list
An array of objects
A merged object.
Merges a list of objects together into one object.
R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3}
R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2}
min Math
-
Array
list
A list of numbers
The greatest number in the list.
Determines the smallest of a list of numbers (or elements that can be cast to numbers)
R.min([7, 3, 9, 2, 4, 9, 3]); //=> 2
minBy Math
-
function
keyFn
A comparator function for elements in the list
-
Array
list
A list of comparable elements
The greatest element in the list. undefined
if the list is empty.
Determines the smallest of a list of items as determined by pairwise comparisons from the supplied comparator Note that this will return undefined if supplied an empty list.
function cmp(obj) { return obj.x; }
var a = {x: 1}, b = {x: 2}, c = {x: 3};
R.minBy(cmp, [a, b, c]); //=> {x: 1}
modulo Math
-
Number
a
The value to the divide.
-
Number
b
The pseudo-modulus
The result of b % a
.
Divides the second parameter by the first and returns the remainder.
Note that this functions preserves the JavaScript-style behavior for
modulo. For mathematical modulo see mathMod
R.modulo(17, 3); //=> 2
// JS behavior:
R.modulo(-17, 3); //=> -2
R.modulo(17, -3); //=> 2
var isOdd = R.modulo(R.__, 2);
isOdd(42); //=> 0
isOdd(21); //=> 1
multiply Math
-
Number
a
The first value.
-
Number
b
The second value.
The result of a * b
.
Multiplies two numbers. Equivalent to a * b
but curried.
var double = R.multiply(2);
var triple = R.multiply(3);
double(3); //=> 6
triple(4); //=> 12
R.multiply(2, 5); //=> 10
nAry Function
-
Number
n
The desired arity of the new function.
-
function
fn
The function to wrap.
A new function wrapping fn
. The new function is guaranteed to be of
arity n
.
Wraps a function of any arity (including nullary) in a function that accepts exactly n
parameters. Any extraneous parameters will not be passed to the supplied function.
var takesTwoArgs = function(a, b) {
return [a, b];
};
takesTwoArgs.length; //=> 2
takesTwoArgs(1, 2); //=> [1, 2]
var takesOneArg = R.nAry(1, takesTwoArgs);
takesOneArg.length; //=> 1
// Only `n` arguments are passed to the wrapped function
takesOneArg(1, 2); //=> [1, undefined]
negate Math
- Number n
Negates its argument.
R.negate(42); //=> -42
none List
-
function
fn
The predicate function.
-
Array
list
The array to consider.
true
if the predicate is not satisfied by every element, false
otherwise.
Returns true
if no elements of the list match the predicate,
false
otherwise.
R.none(R.isNaN, [1, 2, 3]); //=> true
R.none(R.isNaN, [1, 2, 3, NaN]); //=> false
not Logic
-
*
a
any value
the logical inverse of passed argument.
A function that returns the !
of its argument. It will return true
when
passed false-y value, and false
when passed a truth-y one.
R.not(true); //=> false
R.not(false); //=> true
R.not(0); => true
R.not(1); => false
nth List
- Number idx
- Array list
The nth element of the list.
Returns the nth element in a list. If n is negative the element at index length + n is returned.
var list = ['foo', 'bar', 'baz', 'quux'];
R.nth(1, list); //=> 'bar'
R.nth(-1, list); //=> 'quux'
R.nth(-99, list); //=> undefined
nthArg Function
- Number n
Returns a function which returns its nth argument.
R.nthArg(1)('a', 'b', 'c'); //=> 'b'
R.nthArg(-1)('a', 'b', 'c'); //=> 'c'
nthChar String
- Number n
- String str
Returns the nth character of the given string.
R.nthChar(2, 'Ramda'); //=> 'm'
R.nthChar(-2, 'Ramda'); //=> 'd'
nthCharCode String
- Number n
- String str
Returns the character code of the nth character of the given string.
R.nthCharCode(2, 'Ramda'); //=> 'm'.charCodeAt(0)
R.nthCharCode(-2, 'Ramda'); //=> 'd'.charCodeAt(0)
of Function
-
*
x
any value
An array wrapping x
.
Returns a singleton array containing the value provided.
Note this of
is different from the ES6 of
; See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of
R.of(null); //=> [null]
R.of([42]); //=> [[42]]
omit Object
-
Array
names
an array of String property names to omit from the new object
-
Object
obj
The object to copy from
A new object with properties from names
not on it.
Returns a partial copy of an object omitting the keys specified.
R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}
once Function
-
function
fn
The function to wrap in a call-only-once wrapper.
The wrapped function.
Accepts a function fn
and returns a function that guards invocation of fn
such that
fn
can only ever be called once, no matter how many times the returned function is
invoked.
var addOneOnce = R.once(function(x){ return x + 1; });
addOneOnce(10); //=> 11
addOneOnce(addOneOnce(50)); //=> 11
or Logic
-
*
a
any value
-
*
b
any other value
the first truthy argument, otherwise the last argument.
A function that returns the first truthy of two arguments otherwise the last argument. Note that this is NOT short-circuited, meaning that if expressions are passed they are both evaluated.
Dispatches to the or
method of the first argument if applicable.
R.or(false, true); //=> true
R.or(0, []); //=> []
R.or(null, ''); => ''
partial Function
-
function
fn
The function to invoke.
-
*
args
Arguments to prepend to
fn
when the returned function is invoked.
A new function wrapping fn
. When invoked, it will call fn
with args
prepended to fn
's arguments list.
Accepts as its arguments a function and any number of values and returns a function that,
when invoked, calls the original function with all of the values prepended to the
original function's arguments list. In some libraries this function is named applyLeft
.
var multiply = function(a, b) { return a * b; };
var double = R.partial(multiply, 2);
double(2); //=> 4
var greet = function(salutation, title, firstName, lastName) {
return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
};
var sayHello = R.partial(greet, 'Hello');
var sayHelloToMs = R.partial(sayHello, 'Ms.');
sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!'
partialRight Function
-
function
fn
The function to invoke.
-
*
args
Arguments to append to
fn
when the returned function is invoked.
A new function wrapping fn
. When invoked, it will call fn
with
args
appended to fn
's arguments list.
Accepts as its arguments a function and any number of values and returns a function that, when invoked, calls the original function with all of the values appended to the original function's arguments list.
Note that partialRight
is the opposite of partial
: partialRight
fills fn
's arguments
from the right to the left. In some libraries this function is named applyRight
.
var greet = function(salutation, title, firstName, lastName) {
return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
};
var greetMsJaneJones = R.partialRight(greet, 'Ms.', 'Jane', 'Jones');
greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!'
partition List
-
function
pred
A predicate to determine which array the element belongs to.
-
Array
list
The array to partition.
A nested array, containing first an array of elements that satisfied the predicate, and second an array of elements that did not satisfy.
Takes a predicate and a list and returns the pair of lists of elements which do and do not satisfy the predicate, respectively.
R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']);
//=> [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ]
path Object
-
Array
path
The path to use.
The data at path
.
Retrieve the value at a given path.
R.path(['a', 'b'], {a: {b: 2}}); //=> 2
pathEq Relation
-
Array
path
The path of the nested property to use
-
*
val
The value to compare the nested property with
-
Object
obj
The object to check the nested property in
true
if the value equals the nested object property,
false
otherwise.
Determines whether a nested path on an object has a specific value,
in R.equals
terms. Most likely used to filter a list.
var user1 = { address: { zipCode: 90210 } };
var user2 = { address: { zipCode: 55555 } };
var user3 = { name: 'Bob' };
var users = [ user1, user2, user3 ];
var isFamous = R.pathEq(['address', 'zipCode'], 90210);
R.filter(isFamous, users); //=> [ user1 ]
pick Object
-
Array
names
an array of String property names to copy onto a new object
-
Object
obj
The object to copy from
A new object with only properties from names
on it.
Returns a partial copy of an object containing only the keys specified. If the key does not exist, the property is ignored.
R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1}
pickAll Object
-
Array
names
an array of String property names to copy onto a new object
-
Object
obj
The object to copy from
A new object with only properties from names
on it.
Similar to pick
except that this one includes a key: undefined
pair for properties that don't exist.
R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined}
pickBy Object
-
function
pred
A predicate to determine whether or not a key should be included on the output object.
-
Object
obj
The object to copy from
A new object with only properties that satisfy pred
on it.
Returns a partial copy of an object containing only the keys that satisfy the supplied predicate.
var isUpperCase = function(val, key) { return key.toUpperCase() === key; }
R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
pipe Function
-
function
functions
A variable number of functions.
A new function which represents the result of calling each of the
input functions
, passing the result of each function call to the next, from
left to right.
Creates a new function that runs each of the functions supplied as parameters in turn, passing the return value of each function invocation to the next function invocation, beginning with whatever arguments were passed to the initial invocation.
pipe
is the mirror version of compose
. pipe
is left-associative, which means that
each of the functions provided is executed in order from left to right.
In some libraries this function is named sequence
.
var triple = function(x) { return x * 3; };
var double = function(x) { return x * 2; };
var square = function(x) { return x * x; };
var squareThenDoubleThenTriple = R.pipe(square, double, triple);
//≅ triple(double(square(5)))
squareThenDoubleThenTriple(5); //=> 150
pipeL Function
-
function
lenses
A variable number of lenses.
A new lens which represents the result of calling each of the
input lenses
, passing the result of each getter/setter as the source
to the next, from right to left.
Creates a new lens that allows getting and setting values of nested properties, by following each given lens in succession.
pipeL
is the mirror version of composeL
. pipeL
is left-associative, which means that
each of the functions provided is executed in order from left to right.
var headLens = R.lensIndex(0);
var secondLens = R.lensIndex(1);
var xLens = R.lensProp('x');
var headThenXThenSecondLens = R.pipeL(headLens, xLens, secondLens);
var source = [{x: [0, 1], y: [2, 3]}, {x: [4, 5], y: [6, 7]}];
headThenXThenSecondLens(source); //=> 1
headThenXThenSecondLens.set(123, source); //=> [{x: [0, 123], y: [2, 3]}, {x: [4, 5], y: [6, 7]}]
pipeP Function
-
function
functions
A variable number of functions.
A new function which represents the result of calling each of the
input functions
, passing either the returned result or the asynchronously
resolved value) of each function call to the next, from left to right.
Creates a new function that runs each of the functions supplied as parameters in turn,
passing to the next function invocation either the value returned by the previous
function or the resolved value if the returned value is a promise. In other words,
if some of the functions in the sequence return promises, pipeP
pipes the values
asynchronously. If none of the functions return promises, the behavior is the same as
that of pipe
.
pipeP
is the mirror version of composeP
. pipeP
is left-associative, which means that
each of the functions provided is executed in order from left to right.
var Q = require('q');
var triple = function(x) { return x * 3; };
var double = function(x) { return x * 2; };
var squareAsync = function(x) { return Q.when(x * x); };
var squareAsyncThenDoubleThenTriple = R.pipeP(squareAsync, double, triple);
//≅ squareAsync(5).then(function(x) { return triple(double(x)) };
squareAsyncThenDoubleThenTriple(5)
.then(function(result) {
// result is 150
});
pluck List
-
Number
key
The key name to pluck off of each object.
-
Array
list
The array to consider.
The list of values for the given key.
Returns a new list by plucking the same named property off all objects in the list supplied.
R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2]
R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3]
prepend List
-
*
el
The item to add to the head of the output list.
-
Array
list
The array to add to the tail of the output list.
A new array.
Returns a new list with the given element at the front, followed by the contents of the list.
R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum']
product Math
-
Array
list
An array of numbers
The product of all the numbers in the list.
Multiplies together all the elements of a list.
R.product([2,4,6,8,100,1]); //=> 38400
project Object
-
Array
props
The property names to project
-
Array
objs
The objects to query
An array of objects with just the props
properties.
Reasonable analog to SQL select
statement.
var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2};
var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7};
var kids = [abby, fred];
R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}]
prop Object
-
String
p
The property name
-
Object
obj
The object to query
The value at obj.p
.
Returns a function that when supplied an object returns the indicated property of that object, if it exists.
R.prop('x', {x: 100}); //=> 100
R.prop('x', {}); //=> undefined
propEq Relation
-
Number
name
The property name (or index) to use.
-
*
val
The value to compare the property with.
true
if the properties are equal, false
otherwise.
Determines whether the given property of an object has a specific value,
in R.equals
terms. Most likely used to filter a list.
var abby = {name: 'Abby', age: 7, hair: 'blond'};
var fred = {name: 'Fred', age: 12, hair: 'brown'};
var rusty = {name: 'Rusty', age: 10, hair: 'brown'};
var alois = {name: 'Alois', age: 15, disposition: 'surly'};
var kids = [abby, fred, rusty, alois];
var hasBrownHair = R.propEq('hair', 'brown');
R.filter(hasBrownHair, kids); //=> [fred, rusty]
propOr Object
-
*
val
The default value.
-
String
p
The name of the property to return.
-
Object
obj
The object to query.
The value of given property of the supplied object or the default value.
If the given, non-null object has an own property with the specified name, returns the value of that property. Otherwise returns the provided default value.
var alice = {
name: 'ALICE',
age: 101
};
var favorite = R.prop('favoriteLibrary');
var favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary');
favorite(alice); //=> undefined
favoriteWithDefault(alice); //=> 'Ramda'
props Object
-
Array
ps
The property names to fetch
-
Object
obj
The object to query
The corresponding values or partially applied function.
Acts as multiple get
: array of keys in, array of values out. Preserves order.
R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2]
R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2]
var fullName = R.compose(R.join(' '), R.props(['first', 'last']));
fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth'
range List
-
Number
from
The first number in the list.
-
Number
to
One more than the last number in the list.
The list of numbers in tthe set [a, b)
.
Returns a list of numbers from from
(inclusive) to to
(exclusive).
R.range(1, 5); //=> [1, 2, 3, 4]
R.range(50, 53); //=> [50, 51, 52]
reduce List
-
function
fn
The iterator function. Receives two values, the accumulator and the current element from the array.
-
*
acc
The accumulator value.
-
Array
list
The list to iterate over.
The final, accumulated value.
Returns a single item by iterating through the list, successively calling the iterator function and passing it an accumulator value and the current value from the array, and then passing the result to the next call.
The iterator function receives two values: (acc, value). It may use R.reduced
to
shortcut the iteration.
Note: R.reduce
does not skip deleted or unassigned indices (sparse arrays), unlike
the native Array.prototype.reduce
method. For more details on this behavior, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
var numbers = [1, 2, 3];
var add = function(a, b) {
return a + b;
};
R.reduce(add, 10, numbers); //=> 16
reduced List
-
*
x
The final value of the reduce.
The wrapped value.
Returns a value wrapped to indicate that it is the final value of the reduce and transduce functions. The returned value should be considered a black box: the internal structure is not guaranteed to be stable.
Note: this optimization is unavailable to functions not explicitly listed above. For instance, it is not currently supported by reduceIndexed, reduceRight, or reduceRightIndexed.
R.reduce(
R.pipe(R.add, R.ifElse(R.lte(10), R.reduced, R.identity)),
0,
[1, 2, 3, 4, 5]) // 10
reduceIndexed List
-
function
fn
The iterator function. Receives four values: the accumulator, the current element from
list
, that element's index, and the entirelist
itself. -
*
acc
The accumulator value.
-
Array
list
The list to iterate over.
The final, accumulated value.
Like reduce
, but passes additional parameters to the predicate function.
The iterator function receives four values: (acc, value, index, list)
Note: R.reduceIndexed
does not skip deleted or unassigned indices (sparse arrays),
unlike the native Array.prototype.reduce
method. For more details on this behavior,
see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
var letters = ['a', 'b', 'c'];
var objectify = function(accObject, elem, idx, list) {
accObject[elem] = idx;
return accObject;
};
R.reduceIndexed(objectify, {}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 }
reduceRight List
-
function
fn
The iterator function. Receives two values, the accumulator and the current element from the array.
-
*
acc
The accumulator value.
-
Array
list
The list to iterate over.
The final, accumulated value.
Returns a single item by iterating through the list, successively calling the iterator function and passing it an accumulator value and the current value from the array, and then passing the result to the next call.
Similar to reduce
, except moves through the input list from the right to the left.
The iterator function receives two values: (acc, value)
Note: R.reduceRight
does not skip deleted or unassigned indices (sparse arrays), unlike
the native Array.prototype.reduce
method. For more details on this behavior, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description
var pairs = [ ['a', 1], ['b', 2], ['c', 3] ];
var flattenPairs = function(acc, pair) {
return acc.concat(pair);
};
R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ]
reduceRightIndexed List
-
function
fn
The iterator function. Receives four values: the accumulator, the current element from
list
, that element's index, and the entirelist
itself. -
*
acc
The accumulator value.
-
Array
list
The list to iterate over.
The final, accumulated value.
Like reduceRight
, but passes additional parameters to the predicate function. Moves through
the input list from the right to the left.
The iterator function receives four values: (acc, value, index, list).
Note: R.reduceRightIndexed
does not skip deleted or unassigned indices (sparse arrays),
unlike the native Array.prototype.reduce
method. For more details on this behavior,
see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description
var letters = ['a', 'b', 'c'];
var objectify = function(accObject, elem, idx, list) {
accObject[elem] = idx;
return accObject;
};
R.reduceRightIndexed(objectify, {}, letters); //=> { 'c': 2, 'b': 1, 'a': 0 }
reject List
-
function
fn
The function called per iteration.
-
Array
list
The collection to iterate over.
The new filtered array.
Similar to filter
, except that it keeps only values for which the given predicate
function returns falsy. The predicate function is passed one argument: (value).
Acts as a transducer if a transformer is given in list position.
var isOdd = function(n) {
return n % 2 === 1;
};
R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4]
rejectIndexed List
-
function
fn
The function called per iteration.
-
Array
list
The collection to iterate over.
The new filtered array.
Like reject
, but passes additional parameters to the predicate function. The predicate
function is passed three arguments: (value, index, list).
var lastTwo = function(val, idx, list) {
return list.length - idx <= 2;
};
R.rejectIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3]
remove List
-
Number
start
The position to start removing elements
-
Number
count
The number of elements to remove
-
Array
list
The list to remove from
A new Array with count
elements from start
removed.
Removes the sub-list of list
starting at index start
and containing
count
elements. Note that this is not destructive: it returns a
copy of the list with the changes.
No lists have been harmed in the application of this function.
R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8]
repeat List
-
*
value
The value to repeat.
-
Number
n
The desired size of the output list.
A new array containing n
value
s.
Returns a fixed list of size n
containing a specified identical value.
R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi']
var obj = {};
var repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}]
repeatedObjs[0] === repeatedObjs[1]; //=> true
replace String
-
RegExp
pattern
A regular expression or a substring to match.
-
String
replacement
The string to replace the matches with.
-
String
str
The String to do the search and replacement in.
The result.
Replace a substring or regex match in a string with a replacement.
R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo'
R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo'
// Use the "g" (global) flag to replace all occurrences:
R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar'
reverse List
-
Array
list
The list to reverse.
A copy of the list in reverse order.
Returns a new list with the same elements as the original list, just in the reverse order.
R.reverse([1, 2, 3]); //=> [3, 2, 1]
R.reverse([1, 2]); //=> [2, 1]
R.reverse([1]); //=> [1]
R.reverse([]); //=> []
scan List
-
function
fn
The iterator function. Receives two values, the accumulator and the current element from the array
-
*
acc
The accumulator value.
-
Array
list
The list to iterate over.
A list of all intermediately reduced values.
Scan is similar to reduce, but returns a list of successively reduced values from the left
var numbers = [1, 2, 3, 4];
var factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24]
slice List
-
Number
fromIndex
The start index (inclusive).
-
Number
toIndex
The end index (exclusive).
-
Array
xs
The list to take elements from.
The slice of xs
from fromIndex
to toIndex
.
Returns a list containing the elements of xs
from fromIndex
(inclusive)
to toIndex
(exclusive).
Dispatches to its third argument's slice
method if present. As a
result, one may replace [a]
with String
in the type signature.
R.slice(1, 3, ['a', 'b', 'c', 'd']); //=> ['b', 'c']
R.slice(1, Infinity, ['a', 'b', 'c', 'd']); //=> ['b', 'c', 'd']
R.slice(0, -1, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c']
R.slice(-3, -1, ['a', 'b', 'c', 'd']); //=> ['b', 'c']
R.slice(0, 3, 'ramda'); //=> 'ram'
sort List
-
function
comparator
A sorting function :: a -> b -> Int
-
Array
list
The list to sort
a new array with its elements sorted by the comparator function.
Returns a copy of the list, sorted according to the comparator function, which should accept two values at a time and return a negative number if the first value is smaller, a positive number if it's larger, and zero if they are equal. Please note that this is a copy of the list. It does not modify the original.
var diff = function(a, b) { return a - b; };
R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7]
sortBy Relation
- function fn
-
Array
list
The list to sort.
A new list sorted by the keys generated by fn
.
Sorts the list according to the supplied function.
var sortByFirstItem = R.sortBy(prop(0));
var sortByNameCaseInsensitive = R.sortBy(compose(R.toLower, prop('name')));
var pairs = [[-1, 1], [-2, 2], [-3, 3]];
sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]]
var alice = {
name: 'ALICE',
age: 101
};
var bob = {
name: 'Bob',
age: -10
};
var clara = {
name: 'clara',
age: 314.159
};
var people = [clara, bob, alice];
sortByNameCaseInsensitive(people); //=> [alice, bob, clara]
split String
-
String
sep
The separator string.
-
String
str
The string to separate into an array.
The array of strings from str
separated by str
.
Splits a string into an array of strings based on the given separator.
var pathComponents = R.split('/');
R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node']
R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd']
strIndexOf String
-
String
c
A string to find.
-
String
str
The string to search in
The first index of c
or -1 if not found.
Finds the first index of a substring in a string, returning -1 if it's not present
R.strIndexOf('c', 'abcdefg'); //=> 2
strLastIndexOf String
-
String
c
A string to find.
-
String
str
The string to search in
The last index of c
or -1 if not found.
Finds the last index of a substring in a string, returning -1 if it's not present
R.strLastIndexOf('a', 'banana split'); //=> 5
substring String
-
Number
fromIndex
The start index (inclusive).
-
Number
toIndex
The end index (exclusive).
-
String
str
The string to slice.
Returns a string containing the characters of str
from fromIndex
(inclusive) to toIndex
(exclusive).
R.substring(2, 5, 'abcdefghijklm'); //=> 'cde'
substringFrom String
- Number fromIndex
- String str
Returns a string containing the characters of str
from fromIndex
(inclusive) to the end of str
.
R.substringFrom(3, 'Ramda'); //=> 'da'
R.substringFrom(-2, 'Ramda'); //=> 'da'
substringTo String
- Number toIndex
- String str
Returns a string containing the first toIndex
characters of str
.
R.substringTo(3, 'Ramda'); //=> 'Ram'
R.substringTo(-2, 'Ramda'); //=> 'Ram'
subtract Math
-
Number
a
The first value.
-
Number
b
The second value.
The result of a - b
.
Subtracts two numbers. Equivalent to a - b
but curried.
R.subtract(10, 8); //=> 2
var minus5 = R.subtract(R.__, 5);
minus5(17); //=> 12
var complementaryAngle = R.subtract(90);
complementaryAngle(30); //=> 60
complementaryAngle(72); //=> 18
sum Math
-
Array
list
An array of numbers
The sum of all the numbers in the list.
Adds together all the elements of a list.
R.sum([2,4,6,8,100,1]); //=> 121
T Function
true
.
A function that always returns true
. Any passed in parameters are ignored.
R.T(); //=> true
tail List
-
Array
list
The array to consider.
A new array containing all but the first element of the input list, or an empty list if the input list is empty.
Returns all but the first element of a list. If the list provided has the tail
method,
it will instead return list.tail()
.
R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum']
take List
-
Number
n
The number of elements to return.
-
Array
xs
The collection to consider.
Returns a new list containing the first n
elements of the given list.
If n > list.length
, returns a list of list.length
elements.
Acts as a transducer if a transformer is given in list position.
R.take(1, ['foo', 'bar', 'baz']); //=> ['foo']
R.take(2, ['foo', 'bar', 'baz']); //=> ['foo', 'bar']
R.take(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
R.take(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
R.take(3, 'ramda'); //=> 'ram'
var personnel = [
'Dave Brubeck',
'Paul Desmond',
'Eugene Wright',
'Joe Morello',
'Gerry Mulligan',
'Bob Bates',
'Joe Dodge',
'Ron Crotty'
];
takeFive(personnel);
//=> ['Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan']
takeWhile List
-
function
fn
The function called per iteration.
-
Array
list
The collection to iterate over.
A new array.
Returns a new list containing the first n
elements of a given list, passing each value
to the supplied predicate function, and terminating when the predicate function returns
false
. Excludes the element that caused the predicate function to fail. The predicate
function is passed one argument: (value).
Acts as a transducer if a transformer is given in list position.
var isNotFour = function(x) {
return !(x === 4);
};
R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3]
tap Function
-
function
fn
The function to call with
x
. The return value offn
will be thrown away. - * x
x
.
Runs the given function with the supplied object, then returns the object.
var sayX = function(x) { console.log('x is ' + x); };
R.tap(sayX, 100); //=> 100
//-> 'x is 100'
test String
- RegExp pattern
- String str
Determines whether a given string matches a given regular expression.
R.test(/^x/, 'xyz'); //=> true
R.test(/^y/, 'xyz'); //=> false
times List
-
function
fn
The function to invoke. Passed one argument, the current value of
n
. -
Number
n
A value between
0
andn - 1
. Increments after each function call.
An array containing the return values of all calls to fn
.
Calls an input function n
times, returning an array containing the results of those
function calls.
fn
is passed one argument: The current value of n
, which begins at 0
and is
gradually incremented to n - 1
.
R.times(R.identity, 5); //=> [0, 1, 2, 3, 4]
toLower String
-
String
str
The string to lower case.
The lower case version of str
.
The lower case version of a string.
R.toLower('XYZ'); //=> 'xyz'
toPairs Object
-
Object
obj
The object to extract from
An array of key, value arrays from the object's own properties.
Converts an object into an array of key, value arrays. Only the object's own properties are used. Note that the order of the output array is not guaranteed to be consistent across different JS platforms.
R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]]
toPairsIn Object
-
Object
obj
The object to extract from
An array of key, value arrays from the object's own and prototype properties.
Converts an object into an array of key, value arrays. The object's own properties and prototype properties are used. Note that the order of the output array is not guaranteed to be consistent across different JS platforms.
var F = function() { this.x = 'X'; };
F.prototype.y = 'Y';
var f = new F();
R.toPairsIn(f); //=> [['x','X'], ['y','Y']]
toString String
- * val
Returns the string representation of the given value. eval
'ing the output
should result in a value equivalent to the input value. Many of the built-in
toString
methods do not satisfy this requirement.
If the given value is an [object Object]
with a toString
method other
than Object.prototype.toString
, this method is invoked with no arguments
to produce the return value. This means user-defined constructor functions
can provide a suitable toString
method. For example:
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function() {
return 'new Point(' + this.x + ', ' + this.y + ')';
};
R.toString(new Point(1, 2)); //=> 'new Point(1, 2)'
R.toString(42); //=> '42'
R.toString('abc'); //=> '"abc"'
R.toString([1, 2, 3]); //=> '[1, 2, 3]'
R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}'
R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")'
toUpper String
-
String
str
The string to upper case.
The upper case version of str
.
The upper case version of a string.
R.toUpper('abc'); //=> 'ABC'
transduce List
-
function
xf
The transducer function. Receives a transformer and returns a transformer.
-
function
fn
The iterator function. Receives two values, the accumulator and the current element from the array. Wrapped as transformer, if necessary, and used to initialize the transducer
-
*
acc
The initial accumulator value.
-
Array
list
The list to iterate over.
The final, accumulated value.
Initializes a transducer using supplied iterator function. Returns a single item by iterating through the list, successively calling the transformed iterator function and passing it an accumulator value and the current value from the array, and then passing the result to the next call.
The iterator function receives two values: (acc, value). It will be wrapped as a
transformer to initialize the transducer. A transformer can be passed directly in place
of an iterator function. In both cases, iteration may be stopped early with the
R.reduced
function.
A transducer is a function that accepts a transformer and returns a transformer and can be composed directly.
A transformer is an an object that provides a 2-arity reducing iterator function, step, 0-arity initial value function, init, and 1-arity result extraction function, result. The step function is used as the iterator function in reduce. The result function is used to convert the final accumulator into the return type and in most cases is R.identity. The init function can be used to provide an initial accumulator, but is ignored by transduce.
The iteration is performed with R.reduce after initializing the transducer.
var numbers = [1, 2, 3, 4];
var transducer = R.compose(R.map(R.add(1)), R.take(2));
R.transduce(transducer, R.flip(R.append), [], numbers); //=> [2, 3]
trim String
-
String
str
The string to trim.
Trimmed version of str
.
Removes (strips) whitespace from both ends of the string.
R.trim(' xyz '); //=> 'xyz'
R.map(R.trim, R.split(',', 'x, y, z')); //=> ['x', 'y', 'z']
type Type
-
*
val
The value to test
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'.
R.type({}); //=> "Object"
R.type(1); //=> "Number"
R.type(false); //=> "Boolean"
R.type('s'); //=> "String"
R.type(null); //=> "Null"
R.type([]); //=> "Array"
R.type(/[A-z]/); //=> "RegExp"
unapply Function
- function fn
Takes a function fn
, which takes a single array argument, and returns
a function which:
- takes any number of positional arguments;
- passes these arguments to
fn
as an array; and - returns the result.
In other words, R.unapply derives a variadic function from a function which takes an array. R.unapply is the inverse of R.apply.
R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]'
unary Function
-
function
fn
The function to wrap.
A new function wrapping fn
. The new function is guaranteed to be of
arity 1.
Wraps a function of any arity (including nullary) in a function that accepts exactly 1 parameter. Any extraneous parameters will not be passed to the supplied function.
var takesTwoArgs = function(a, b) {
return [a, b];
};
takesTwoArgs.length; //=> 2
takesTwoArgs(1, 2); //=> [1, 2]
var takesOneArg = R.unary(takesTwoArgs);
takesOneArg.length; //=> 1
// Only 1 argument is passed to the wrapped function
takesOneArg(1, 2); //=> [1, undefined]
uncurryN Function
-
Number
length
The arity for the returned function.
-
function
fn
The function to uncurry.
A new function.
Returns a function of arity n
from a (manually) curried function.
var addFour = function(a) {
return function(b) {
return function(c) {
return function(d) {
return a + b + c + d;
};
};
};
};
var uncurriedAddFour = R.uncurryN(4, addFour);
curriedAddFour(1, 2, 3, 4); //=> 10
unfold List
-
function
fn
The iterator function. receives one argument,
seed
, and returns either false to quit iteration or an array of length two to proceed. The element at index 0 of this array will be added to the resulting array, and the element at index 1 will be passed to the next call tofn
. -
*
seed
The seed value.
The final list.
Builds a list from a seed value. Accepts an iterator function, which returns either false to stop iteration or an array of length 2 containing the value to add to the resulting list and the seed to be used in the next call to the iterator function.
The iterator function receives one argument: (seed).
var f = function(n) { return n > 50 ? false : [-n, n + 10] };
R.unfold(f, 10); //=> [-10, -20, -30, -40, -50]
union Relation
-
Array
as
The first list.
-
Array
bs
The second list.
The first and second lists concatenated, with duplicates removed.
Combines two lists into a set (i.e. no duplicates) composed of the elements of each list.
R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4]
unionWith Relation
-
function
pred
A predicate used to test whether two items are equal.
-
Array
list1
The first list.
-
Array
list2
The second list.
The first and second lists concatenated, with duplicates removed.
Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is determined according to the value returned by applying the supplied predicate to two list elements.
function cmp(x, y) { return x.a === y.a; }
var l1 = [{a: 1}, {a: 2}];
var l2 = [{a: 1}, {a: 4}];
R.unionWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}]
uniq List
-
Array
list
The array to consider.
The list of unique items.
Returns a new list containing only one copy of each element in the original list.
R.equals
is used to determine equality.
R.uniq([1, 1, 2, 1]); //=> [1, 2]
R.uniq([1, '1']); //=> [1, '1']
R.uniq([[42], [42]]); //=> [[42]]
uniqWith List
-
function
pred
A predicate used to test whether two items are equal.
-
Array
list
The array to consider.
The list of unique items.
Returns a new list containing only one copy of each element in the original list, based upon the value returned by applying the supplied predicate to two list elements. Prefers the first item if two items compare equal based on the predicate.
var strEq = function(a, b) { return String(a) === String(b); };
R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2]
R.uniqWith(strEq)([{}, {}]); //=> [{}]
R.uniqWith(strEq)([1, '1', 1]); //=> [1]
R.uniqWith(strEq)(['1', 1, 1]); //=> ['1']
unnest List
-
Array
list
The array to consider.
The flattened list.
Returns a new list by pulling every item at the first level of nesting out, and putting them in a new array.
R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]]
R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6]
update List
-
Number
idx
The index to update.
-
*
x
The value to exist at the given index of the returned array.
-
Array
list
The source array-like object to be updated.
A copy of list
with the value at index idx
replaced with x
.
Returns a new copy of the array with the element at the provided index replaced with the given value.
R.update(1, 11, [0, 1, 2]); //=> [0, 11, 2]
R.update(1)(11)([0, 1, 2]); //=> [0, 11, 2]
useWith Function
-
function
fn
The function to wrap.
-
function
transformers
A variable number of transformer functions
The wrapped function.
Accepts a function fn
and any number of transformer functions and returns a new
function. When the new function is invoked, it calls the function fn
with parameters
consisting of the result of calling each supplied handler on successive arguments to the
new function.
If more arguments are passed to the returned function than transformer functions, those
arguments are passed directly to fn
as additional parameters. If you expect additional
arguments that don't need to be transformed, although you can ignore them, it's best to
pass an identity function so that the new function reports the correct arity.
// Example 1:
// Number -> [Person] -> [Person]
var byAge = R.useWith(R.filter, R.propEq('age'), R.identity);
var kids = [
{name: 'Abbie', age: 6},
{name: 'Brian', age: 5},
{name: 'Chris', age: 6},
{name: 'David', age: 4},
{name: 'Ellie', age: 5}
];
byAge(5, kids); //=> [{name: 'Brian', age: 5}, {name: 'Ellie', age: 5}]
// Example 2:
var double = function(y) { return y * 2; };
var square = function(x) { return x * x; };
var add = function(a, b) { return a + b; };
// Adds any number of arguments together
var addAll = function() {
return R.reduce(add, 0, arguments);
};
// Basic example
var addDoubleAndSquare = R.useWith(addAll, double, square);
//≅ addAll(double(10), square(5));
addDoubleAndSquare(10, 5); //=> 45
// Example of passing more arguments than transformers
//≅ addAll(double(10), square(5), 100);
addDoubleAndSquare(10, 5, 100); //=> 145
// If there are extra _expected_ arguments that don't need to be transformed, although
// you can ignore them, it might be best to pass in the identity function so that the new
// function correctly reports arity.
var addDoubleAndSquareWithExtraParams = R.useWith(addAll, double, square, R.identity);
// addDoubleAndSquareWithExtraParams.length //=> 3
//≅ addAll(double(10), square(5), R.identity(100));
addDoubleAndSquare(10, 5, 100); //=> 145
values Object
-
Object
obj
The object to extract values from
An array of the values of the object's own properties.
Returns a list of all the enumerable own properties of the supplied object. Note that the order of the output array is not guaranteed across different JS platforms.
R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3]
valuesIn Object
-
Object
obj
The object to extract values from
An array of the values of the object's own and prototype properties.
Returns a list of all the properties, including prototype properties, of the supplied object. Note that the order of the output array is not guaranteed to be consistent across different JS platforms.
var F = function() { this.x = 'X'; };
F.prototype.y = 'Y';
var f = new F();
R.valuesIn(f); //=> ['X', 'Y']
where Object
- Object spec
- Object testObj
Takes a spec object and a test object; returns true if the test satisfies
the spec. Each of the spec's own properties must be a predicate function.
Each predicate is applied to the value of the corresponding property of
the test object. where
returns true if all the predicates return true,
false otherwise.
where
is well suited to declaratively expressing constraints for other
functions such as filter
and find
.
// pred :: Object -> Boolean
var pred = R.where({
a: R.equals('foo'),
b: R.complement(R.equals('bar')),
x: R.gt(_, 10),
y: R.lt(_, 20)
});
pred({a: 'foo', b: 'xxx', x: 11, y: 19}); //=> true
pred({a: 'xxx', b: 'xxx', x: 11, y: 19}); //=> false
pred({a: 'foo', b: 'bar', x: 11, y: 19}); //=> false
pred({a: 'foo', b: 'xxx', x: 10, y: 19}); //=> false
pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> false
whereEq Object
- Object spec
- Object testObj
Takes a spec object and a test object; returns true if the test satisfies
the spec, false otherwise. An object satisfies the spec if, for each of the
spec's own properties, accessing that property of the object gives the same
value (in R.equals
terms) as accessing that property of the spec.
whereEq
is a specialization of where
.
// pred :: Object -> Boolean
var pred = R.whereEq({a: 1, b: 2});
pred({a: 1}); //=> false
pred({a: 1, b: 2}); //=> true
pred({a: 1, b: 2, c: 3}); //=> true
pred({a: 1, b: 1}); //=> false
wrap Function
-
function
fn
The function to wrap.
-
function
wrapper
The wrapper function.
The wrapped function.
Wrap a function inside another to allow you to make adjustments to the parameters, or do other processing either before the internal function is called or with its results.
var greet = function(name) {return 'Hello ' + name;};
var shoutedGreet = R.wrap(greet, function(gr, name) {
return gr(name).toUpperCase();
});
shoutedGreet("Kathy"); //=> "HELLO KATHY"
var shortenedGreet = R.wrap(greet, function(gr, name) {
return gr(name.substring(0, 3));
});
shortenedGreet("Robert"); //=> "Hello Rob"
xprod List
-
Array
as
The first list.
-
Array
bs
The second list.
The list made by combining each possible pair from
as
and bs
into pairs ([a, b]
).
Creates a new list out of the two supplied by creating each possible pair from the lists.
R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
zip List
-
Array
list1
The first array to consider.
-
Array
list2
The second array to consider.
The list made by pairing up same-indexed elements of list1
and list2
.
Creates a new list out of the two supplied by pairing up
equally-positioned items from both lists. The returned list is
truncated to the length of the shorter of the two input lists.
Note: zip
is equivalent to zipWith(function(a, b) { return [a, b] })
.
R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']]
zipObj List
-
Array
keys
The array that will be properties on the output object.
-
Array
values
The list of values on the output object.
The object made by pairing up same-indexed elements of keys
and values
.
Creates a new object out of a list of keys and a list of values.
R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3}
zipWith List
-
function
fn
The function used to combine the two elements into one value.
-
Array
list1
The first array to consider.
-
Array
list2
The second array to consider.
The list made by combining same-indexed elements of list1
and list2
using fn
.
Creates a new list out of the two supplied by applying the function to each equally-positioned pair in the lists. The returned list is truncated to the length of the shorter of the two input lists.
var f = function(x, y) {
// ...
};
R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']);
//=> [f(1, 'a'), f(2, 'b'), f(3, 'c')]