@types/ramda
- Version 0.28.23
- Published
- 262 kB
- 1 dependency
- MIT license
Install
npm i @types/ramda
yarn add @types/ramda
pnpm add @types/ramda
Overview
TypeScript definitions for ramda
Index
Functions
- add()
- addIndex()
- adjust()
- all()
- allPass()
- always()
- and()
- andThen()
- any()
- anyPass()
- ap()
- aperture()
- append()
- apply()
- applySpec()
- applyTo()
- ascend()
- assoc()
- assocPath()
- binary()
- bind()
- both()
- call()
- chain()
- clamp()
- clone()
- collectBy()
- comparator()
- complement()
- compose()
- composeWith()
- concat()
- cond()
- construct()
- constructN()
- converge()
- count()
- countBy()
- curry()
- curryN()
- dec()
- defaultTo()
- descend()
- difference()
- differenceWith()
- dissoc()
- dissocPath()
- divide()
- drop()
- dropLast()
- dropLastWhile()
- dropRepeats()
- dropRepeatsWith()
- dropWhile()
- either()
- empty()
- endsWith()
- eqBy()
- eqProps()
- equals()
- evolve()
- F()
- filter()
- find()
- findIndex()
- findLast()
- findLastIndex()
- flatten()
- flip()
- forEach()
- forEachObjIndexed()
- fromPairs()
- groupBy()
- groupWith()
- gt()
- gte()
- has()
- hasIn()
- hasPath()
- head()
- identical()
- identity()
- ifElse()
- inc()
- includes()
- indexBy()
- indexOf()
- init()
- innerJoin()
- insert()
- insertAll()
- intersection()
- intersperse()
- into()
- invert()
- invertObj()
- invoker()
- is()
- isEmpty()
- isNil()
- join()
- juxt()
- keys()
- keysIn()
- last()
- lastIndexOf()
- length()
- lens()
- lensIndex()
- lensPath()
- lensProp()
- lift()
- liftN()
- lt()
- lte()
- map()
- mapAccum()
- mapAccumRight()
- mapObjIndexed()
- match()
- mathMod()
- max()
- maxBy()
- mean()
- median()
- memoizeWith()
- mergeAll()
- mergeDeepLeft()
- mergeDeepRight()
- mergeDeepWith()
- mergeDeepWithKey()
- mergeLeft()
- mergeRight()
- mergeWith()
- mergeWithKey()
- min()
- minBy()
- modify()
- modulo()
- move()
- multiply()
- nAry()
- negate()
- none()
- not()
- nth()
- nthArg()
- o()
- objOf()
- of()
- omit()
- on()
- once()
- or()
- otherwise()
- over()
- pair()
- partial()
- partialObject()
- partialRight()
- partition()
- path()
- pathEq()
- pathOr()
- paths()
- pathSatisfies()
- pick()
- pickAll()
- pickBy()
- pipe()
- pipeWith()
- pluck()
- prepend()
- product()
- project()
- promap()
- prop()
- propEq()
- propIs()
- propOr()
- props()
- propSatisfies()
- range()
- reduce()
- reduceBy()
- reduced()
- reduceRight()
- reduceWhile()
- reject()
- remove()
- repeat()
- replace()
- reverse()
- scan()
- set()
- slice()
- sort()
- sortBy()
- sortWith()
- split()
- splitAt()
- splitEvery()
- splitWhen()
- splitWhenever()
- startsWith()
- subtract()
- sum()
- symmetricDifference()
- symmetricDifferenceWith()
- T()
- tail()
- take()
- takeLast()
- takeLastWhile()
- takeWhile()
- tap()
- test()
- thunkify()
- times()
- toLower()
- toPairs()
- toPairsIn()
- toString()
- toUpper()
- transduce()
- transpose()
- traverse()
- trim()
- tryCatch()
- type()
- unapply()
- unary()
- uncurryN()
- unfold()
- union()
- unionWith()
- uniq()
- uniqBy()
- uniqWith()
- unless()
- unnest()
- until()
- update()
- useWith()
- values()
- valuesIn()
- view()
- when()
- where()
- whereEq()
- without()
- xor()
- xprod()
- zip()
- zipObj()
- zipWith()
Interfaces
Type Aliases
- AnyConstructor
- AnyFunction
- Arity0Fn
- Arity1Fn
- Arity2Fn
- AssocPartialOne
- AtLeastOneFunctionsFlow
- AtLeastOneFunctionsFlowFromRightToLeft
- CondPair
- CondPairTypeguard
- EQ
- Evolvable
- Evolve
- Evolver
- Falsy
- Fn
- Functor
- GT
- IfFunctionsArgumentsDoNotOverlap
- InputTypesOfFns
- KeyValuePair
- LargestArgumentsList
- Lens
- LT
- Merge
- MergeAll
- mergeArrWithLeft
- ObjectHavingSome
- ObjPred
- Ord
- Ordering
- Path
- Placeholder
- Pred
- PredTypeguard
- Prop
- ReturnTypesOfFns
- Take
- ToTupleOfArray
- ToTupleOfFunction
- Tuple
- ValueOfRecord
- ValueOfUnion
Functions
function add
add: { (a: number, b: number): number; (a: number): (b: number) => number };
Adds two values. Equivalent to
a + b
but curried.Example 1
R.add(2, 3); //=> 5R.add(7)(10); //=> 17
function addIndex
addIndex: { <T>(fn: (f: (item: T) => void, list: readonly T[]) => T[]): _.F.Curry< (a: (item: T, idx: number, list: T[]) => void, b: readonly T[]) => T[] >; <T>(fn: (f: (item: T) => boolean, list: readonly T[]) => T[]): _.F.Curry< (a: (item: T, idx: number, list: T[]) => boolean, b: readonly T[]) => T[] >; <T, U>(fn: (f: (item: T) => U, list: readonly T[]) => U[]): _.F.Curry< (a: (item: T, idx: number, list: T[]) => U, b: readonly T[]) => U[] >; <T, U>( fn: (f: (acc: U, item: T) => U, aci: U, list: readonly T[]) => U ): _.F.Curry< ( a: (acc: U, item: T, idx: number, list: T[]) => U, b: U, c: readonly T[] ) => U >;};
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, function into one that more closely resembles
Array.prototype.map
.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.)
See also subtract.
Example 1
const mapIndexed = R.addIndex(R.map);mapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']);//=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r']
function adjust
adjust: { <T>(index: number, fn: (a: T) => T, list: readonly T[]): T[]; <T>(index: number, fn: (a: T) => T): (list: readonly T[]) => T[];};
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.
See also update.
Example 1
R.adjust(1, R.toUpper, ['a', 'b', 'c', 'd']); //=> ['a', 'B', 'c', 'd']R.adjust(-1, R.toUpper, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c', 'D']
function all
all: { <T>(fn: (a: T) => boolean, list: readonly T[]): boolean; <T>(fn: (a: T) => boolean): (list: readonly T[]) => boolean;};
Returns
true
if all elements of the list match the predicate,false
if there are any that don't.Dispatches to the
all
method of the second argument, if present.Acts as a transducer if a transformer is given in list position.
Example 1
const equals3 = R.equals(3);R.all(equals3)([3, 3, 3, 3]); //=> trueR.all(equals3)([3, 3, 1, 3]); //=> false
function allPass
allPass: { <T, TF1 extends T, TF2 extends T>( preds: [PredTypeguard<T, TF1>, PredTypeguard<T, TF2>] ): (a: T) => a is TF1 & TF2; <T, TF1 extends T, TF2 extends T, TF3 extends T>( preds: [PredTypeguard<T, TF1>, PredTypeguard<T, TF2>, PredTypeguard<T, TF3>] ): (a: T) => a is TF1 & TF2 & TF3; <T, TF1 extends T, TF2 extends T, TF3 extends T>( preds: [PredTypeguard<T, TF1>, PredTypeguard<T, TF2>, PredTypeguard<T, TF3>] ): (a: T) => a is TF1 & TF2 & TF3; <T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T>( preds: [ PredTypeguard<T, TF1>, PredTypeguard<T, TF2>, PredTypeguard<T, TF3>, PredTypeguard<T, TF4> ] ): (a: T) => a is TF1 & TF2 & TF3 & TF4; <T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T, TF5 extends T>( preds: [ PredTypeguard<T, TF1>, PredTypeguard<T, TF2>, PredTypeguard<T, TF3>, PredTypeguard<T, TF4>, PredTypeguard<T, TF5> ] ): PredTypeguard<T, TF1 & TF2 & TF3 & TF4 & TF5>; < T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T, TF5 extends T, TF6 extends T >( preds: [ PredTypeguard<T, TF1>, PredTypeguard<T, TF2>, PredTypeguard<T, TF3>, PredTypeguard<T, TF4>, PredTypeguard<T, TF5>, PredTypeguard<T, TF6> ] ): PredTypeguard<T, TF1 & TF2 & TF3 & TF4 & TF5 & TF6>; <F extends Pred<any[]>>(preds: readonly F[]): F;};
Takes a list of predicates and returns a predicate that returns true for a given list of arguments if every one of the provided predicates is satisfied by those arguments.
The function returned is a curried function whose arity matches that of the highest-arity predicate.
See also anyPass.
Example 1
type Card = { rank: string; suit: string; };const isQueen = R.propEq('rank', 'Q');const isSpade = R.propEq('suit', '♠︎');const isQueenOfSpades = R.allPass<R.Pred<[Card]>>([isQueen, isSpade]);isQueenOfSpades({rank: 'Q', suit: '♣︎'}); //=> falseisQueenOfSpades({rank: 'Q', suit: '♠︎'}); //=> true
function always
always: <T>(val: T) => (...args: unknown[]) => T;
Returns a function that always returns the given value.
For non-primitives the value returned is a reference to the original value.
This function is known as
const
,constant
, orK
(for K combinator) in other languages and libraries.Example 1
const t = R.always('Tee');t(); //=> 'Tee'
function and
and: { <T, U>(a: T, b: U): T | U; <T>(a: T): <U>(b: U) => T | U };
A function that returns the first argument if it's falsy otherwise the second argument.
This is **not** short-circuited, meaning that if expressions are passed they are both evaluated.
Example 1
R.and(true, true); //=> trueR.and(true, false); //=> falseR.and(false, true); //=> falseR.and(false, false); //=> false
function andThen
andThen: { <A, B>(onSuccess: (a: A) => B | Promise<B>, promise: Promise<A>): Promise<B>; <A, B>(onSuccess: (a: A) => B | Promise<B>): (promise: Promise<A>) => Promise<B>;};
Returns the result of applying the
onSuccess
function to the value inside a successfully resolvedPromise
. This is useful for working withPromise
s inside function compositions.See also otherwise.
Example 1
type Query = { query: { email: string; }; };const makeQuery = (email: string) => ({ query: { email }});const fetchMember = (request: Query) =>Promise.resolve({ firstName: 'Bob', lastName: 'Loblaw', id: 42 });//getMemberName :: String -> Promise ({ firstName, lastName })const getMemberName = R.pipe(makeQuery,fetchMember,R.andThen(R.pick(['firstName', 'lastName'])));getMemberName('bob@gmail.com').then(console.log);
function any
any: { <T>(fn: (a: T) => boolean, list: readonly T[]): boolean; <T>(fn: (a: T) => boolean): (list: readonly T[]) => boolean;};
Returns
true
if at least one of elements of the list match the predicate,false
otherwise.Dispatches to the
any
method of the second argument, if present.Acts as a transducer if a transformer is given in list position.
Example 1
const lessThan0 = R.flip(R.lt)(0);const lessThan2 = R.flip(R.lt)(2);R.any(lessThan0)([1, 2]); //=> falseR.any(lessThan2)([1, 2]); //=> true
function anyPass
anyPass: { <T, TF1 extends T, TF2 extends T>( preds: [PredTypeguard<T, TF1>, PredTypeguard<T, TF2>] ): (a: T) => a is TF1 | TF2; <T, TF1 extends T, TF2 extends T, TF3 extends T>( preds: [PredTypeguard<T, TF1>, PredTypeguard<T, TF2>, PredTypeguard<T, TF3>] ): (a: T) => a is TF1 | TF2 | TF3; <T, TF1 extends T, TF2 extends T, TF3 extends T>( preds: [PredTypeguard<T, TF1>, PredTypeguard<T, TF2>, PredTypeguard<T, TF3>] ): (a: T) => a is TF1 | TF2 | TF3; <T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T>( preds: [ PredTypeguard<T, TF1>, PredTypeguard<T, TF2>, PredTypeguard<T, TF3>, PredTypeguard<T, TF4> ] ): (a: T) => a is TF1 | TF2 | TF3 | TF4; <T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T, TF5 extends T>( preds: [ PredTypeguard<T, TF1>, PredTypeguard<T, TF2>, PredTypeguard<T, TF3>, PredTypeguard<T, TF4>, PredTypeguard<T, TF5> ] ): PredTypeguard<T, TF1 | TF2 | TF3 | TF4 | TF5>; < T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T, TF5 extends T, TF6 extends T >( preds: [ PredTypeguard<T, TF1>, PredTypeguard<T, TF2>, PredTypeguard<T, TF3>, PredTypeguard<T, TF4>, PredTypeguard<T, TF5>, PredTypeguard<T, TF6> ] ): PredTypeguard<T, TF1 | TF2 | TF3 | TF4 | TF5 | TF6>; <F extends Pred<any[]>>(preds: readonly F[]): F;};
Takes a list of predicates and returns a predicate that returns true for a given list of arguments if at least one of the provided predicates is satisfied by those arguments.
The function returned is a curried function whose arity matches that of the highest-arity predicate.
See also allPass.
Example 1
type Card = { rank: string; suit: string; };const isClub = R.propEq('suit', '♣');const isSpade = R.propEq('suit', '♠');const isBlackCard = R.anyPass<R.Pred<[Card]>>([isClub, isSpade]);isBlackCard({rank: '10', suit: '♣'}); //=> trueisBlackCard({rank: 'Q', suit: '♠'}); //=> trueisBlackCard({rank: 'Q', suit: '♦'}); //=> false
function ap
ap: { <T, U>(fns: readonly ((a: T) => U)[], vs: readonly T[]): U[]; <T, U>(fns: readonly ((a: T) => U)[]): (vs: readonly T[]) => U[]; <R, A, B>(fn: (r: R, a: A) => B, fn1: (r: R) => A): (r: R) => B;};
ap
applies a list of functions to a list of values.Dispatches to the
ap
method of the first argument, if present. Also treats curried functions as applicatives.Example 1
R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6]R.ap([R.concat('tasty '), R.toUpper], ['pizza', 'salad']); //=> ["tasty pizza", "tasty salad", "PIZZA", "SALAD"]// R.ap can also be used as S combinator// when only two functions are passedR.ap((s, s2) => R.concat(s, s2), R.toUpper)('Ramda') //=> 'RamdaRAMDA'
function aperture
aperture: { <N extends number, T>(n: N, list: readonly T[]): Array<Tuple<T, N>> | []; <N extends number>(n: N): <T>(list: readonly T[]) => [] | Tuple<T, N>[];};
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.Acts as a transducer if a transformer is given in list position.
See also transduce.
Example 1
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]); //=> []
function append
append: { <T>(el: T, list: readonly T[]): T[]; <T>(el: T): (list: readonly T[]) => T[];};
Returns a new list containing the contents of the given list, followed by the given element.
See also prepend.
Example 1
R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests']R.append('tests', []); //=> ['tests']R.append<string | string[]>(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']]
function apply
apply: { <F extends AnyFunction>(fn: F, args: Parameters<F>): ReturnType<F>; <F extends AnyFunction>(fn: F): (args: Parameters<F>) => ReturnType<F>;};
function applySpec
applySpec: { <Obj extends Record<string, AnyFunction>>(obj: Obj): ( ...args: Parameters<Obj[keyof Obj]> ) => { [Key in keyof Obj]: ReturnType<Obj[Key]> }; <T>(obj: any): (...args: unknown[]) => T;};
Given a spec object recursively mapping properties to functions, creates a function producing an object of the same structure, by mapping each property to the result of calling its associated function with the supplied arguments.
Example 1
const getMetrics = R.applySpec({sum: R.add,nested: { mul: R.multiply }});getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } }
function applyTo
applyTo: { <T, U>(el: T, fn: (t: T) => U): U; <T>(el: T): <U>(fn: (t: T) => U) => U;};
Takes a value and applies a function to it.
This function is also known as the
thrush
combinator.Example 1
const t42 = R.applyTo(42);t42(R.identity); //=> 42t42(R.add(1)); //=> 43
function ascend
ascend: { <T>(fn: (obj: T) => Ord, a: T, b: T): Ordering; <T>(fn: (obj: T) => Ord): (a: T, b: T) => Ordering;};
Makes an ascending comparator function out of a function that returns a value that can be compared with
<
and>
.See also descend.
Example 1
const byAge = R.ascend(R.prop<number>('age'));const people = [{ name: 'Emma', age: 70 },{ name: 'Peter', age: 78 },{ name: 'Mikhail', age: 62 },];const peopleByYoungestFirst = R.sort(byAge, people);//=> [{ name: 'Mikhail', age: 62 },{ name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }]
function assoc
assoc: { <T, U>(__: Placeholder, val: T, obj: U): <K extends string>( prop: K ) => K extends keyof U ? T extends U[K] ? U : Record<K, T> & Omit<U, K> : Record<K, T> & Omit<U, K>; <U, K extends keyof U>(prop: K, __: any, obj: U): <T>( val: T ) => T extends U[K] ? U : Record<K, T> & Omit<U, K>; <U, K extends string>(prop: K, __: any, obj: U): <T>( val: T ) => Record<K, T> & Omit<U, K>; <K extends keyof U, U>(prop: K, val: U[K], obj: U): U; <T, U, K extends string>(prop: K, val: T, obj: U): Record<K, T> & Omit<U, K>; <T, K extends string>(prop: K, val: T): <U>(obj: U) => Record<K, T> & Omit<U, K>; <K extends string>(prop: K): AssocPartialOne<K>;};
Makes a shallow clone of an object, setting or overriding the specified property with the given value.
This copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference.
Example 1
R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3}
function assocPath
assocPath: { <T, U>(__: Placeholder, val: T, obj: U): (path: Path) => U; <T, U>(path: Path, __: any, obj: U): (val: T) => U; <T, U>(path: Path, val: T, obj: U): U; <T, U>(path: Path, val: T): (obj: U) => U; <T, U>(path: Path): _.F.Curry<(a: T, b: U) => U>;};
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.
This copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference.
See also dissocPath.
Example 1
R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}}// Any missing or non-object keys in path will be overriddenR.assocPath(['a', 'b', 'c'], 42, {a: 5}); //=> {a: {b: {c: 42}}}
function binary
binary: <T extends AnyFunction>( fn: T) => (...arg: _.T.Take<Parameters<T>, '2'>) => ReturnType<T>;
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.
Example 1
const takesThreeArgs = function(a: number, b: number, c: number) {return [a, b, c];};takesThreeArgs.length; //=> 3takesThreeArgs(1, 2, 3); //=> [1, 2, 3]const takesTwoArgs = R.binary(takesThreeArgs);takesTwoArgs.length; //=> 2// Only 2 arguments are passed to the wrapped function// @ts-expect-error TypeScript is designed to not let you do thistakesTwoArgs(1, 2, 3); //=> [1, 2, undefined]
function bind
bind: { <F extends AnyFunction, T>(fn: F, thisObj: T): ( ...args: Parameters<F> ) => ReturnType<F>; <F extends AnyFunction, T>(fn: F): ( thisObj: T ) => (...args: Parameters<F>) => ReturnType<F>;};
Creates a function that is bound to a context.
R.bind
does not provide the additional argument-binding capabilities ofFunction.prototype.bind
.Example 1
const log = R.bind(console.log, console);R.pipe(R.assoc('a', 2), R.tap(log), R.assoc('a', 3))({a: 1}); //=> {a: 3}// logs {a: 2}
function both
both: { <T, TF1 extends T, TF2 extends T>( pred1: PredTypeguard<T, TF1>, pred2: PredTypeguard<T, TF2> ): (a: T) => a is TF1 & TF2; <T extends Pred<any[]>>(pred1: T, pred2: T): T; <T extends Pred<any[]>>(pred1: T): (pred2: T) => T;};
A function which calls the two provided functions and returns the
&&
of the results. It returns the result of the first function if it is falsy and the result of the second function otherwise.This is short-circuited, meaning that the second function will not be invoked if the first returns a falsy value.
In addition to functions,
R.both
also accepts any fantasy-land compatible applicative functor.Example 1
const gt10 = R.gt(R.__, 10)const lt20 = R.lt(R.__, 20)const f = R.both(gt10, lt20);f(15); //=> truef(30); //=> false
function call
call: <T extends AnyFunction>(fn: T, ...args: Parameters<T>) => ReturnType<T>;
Returns the result of calling its first argument with the remaining arguments. This is occasionally useful as a converging function for : the first branch can produce a function while the remaining branches produce values to be passed to that function as its arguments.
See also apply.
Example 1
R.call<(a: number, b: number) => number>(R.add, 1, 2); //=> 3const indentN = R.pipe(R.repeat(' '),R.join(''),R.replace(/^(?!$)/gm));
function chain
chain: { <A, B, T = never>(fn: (n: A) => readonly B[], list: readonly A[]): B[]; <A, B, T = never>(fn: (n: A) => readonly B[]): (list: readonly A[]) => B[]; <A, Ma extends { chain: (fn: (a: A) => Mb) => Mb }, Mb>( fn: (a: A) => Mb, monad: Ma ): Mb; <A, Ma extends { chain: (fn: (a: A) => Mb) => Mb }, Mb>(fn: (a: A) => Mb): ( monad: Ma ) => Mb; <A, B, R>(aToMb: (a: A, r: R) => B, Ma: (r: R) => A): (r: R) => B; <A, B, R>(aToMb: (a: A, r: R) => B): (Ma: (r: R) => A) => (r: R) => B;};
chain
maps a function over a list and concatenates the results.chain
is also known asflatMap
in some libraries.Dispatches to the
chain
method of the second argument, if present, according to the FantasyLand Chain spec.If second argument is a function,
chain(f, g)(x)
is equivalent tof(g(x), x)
.Acts as a transducer if a transformer is given in list position.
See also transduce.
Example 1
const duplicate = <T>(n: T) => [n, n];R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]R.chain(R.append, R.head)([1, 2, 3]); //=> [1, 2, 3, 1]
function clamp
clamp: { <T>(min: T, max: T, value: T): T; <T>(min: T, max: T): (value: T) => T; <T>(min: T): (max: T, value: T) => T; <T>(min: T): (max: T) => (value: T) => T;};
Restricts a number to be within a range. Also works for other ordered types such as strings and
Date
s.Example 1
R.clamp(1, 10, -5) // => 1R.clamp(1, 10, 15) // => 10R.clamp(1, 10, 4) // => 4
function clone
clone: { <T>(value: T): T; <T>(value: readonly T[]): T[] };
Creates a deep copy of the source that can be used in place of the source object without retaining any references to it. The source object may contain (nested)
Array
s andObject
s, numbers, strings, booleans andDate
s.Functions
are assigned by reference rather than copied.Dispatches to a
clone
method if present.Note that if the source object has multiple nodes that share a reference, the returned object will have the same structure, but the references will be pointed to the location within the cloned value.
Example 1
const objects = [{}, {}, {}];const objectsClone = R.clone(objects);objects === objectsClone; //=> falseobjects[0] === objectsClone[0]; //=> false
function collectBy
collectBy: { <T, K extends PropertyKey>(keyFn: (value: T) => K, list: readonly T[]): T[][]; <T, K extends PropertyKey>(keyFn: (value: T) => K): ( list: readonly T[] ) => T[][];};
Splits a list into sub-lists, based on the result of calling a key-returning function on each element, and grouping the results according to values returned.
Example 1
R.collectBy(R.prop('type'), [{type: 'breakfast', item: '☕️'},{type: 'lunch', item: '🌯'},{type: 'dinner', item: '🍝'},{type: 'breakfast', item: '🥐'},{type: 'lunch', item: '🍕'}]);// [ [ {type: 'breakfast', item: '☕️'},// {type: 'breakfast', item: '🥐'} ],// [ {type: 'lunch', item: '🌯'},// {type: 'lunch', item: '🍕'} ],// [ {type: 'dinner', item: '🍝'} ] ]
function comparator
comparator: <T>(pred: (a: T, b: T) => boolean) => (x: T, y: T) => Ordering;
Makes a comparator function out of a function that reports whether the first element is less than the second.
Example 1
type Person = { name: string; age: number; };const byAge = R.comparator<Person>((a, b) => a.age < b.age);const people = [{ name: 'Emma', age: 70 },{ name: 'Peter', age: 78 },{ name: 'Mikhail', age: 62 },];const peopleByIncreasingAge = R.sort(byAge, people);//=> [{ name: 'Mikhail', age: 62 },{ name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }]
function complement
complement: { <T, TFiltered extends T>(pred: (value: T) => value is TFiltered): ( value: T ) => value is Exclude<T, TFiltered>; <TArgs extends any[]>(pred: (...args: TArgs) => unknown): ( ...args: TArgs ) => boolean;};
Takes a function
f
and returns a functiong
such that if called with the same arguments whenf
returns a truthy value,g
returnsfalse
and whenf
returns a falsy valueg
returnstrue
.R.complement
may be applied to any functor.See also not.
Example 1
const isNotNil = R.complement(R.isNil);R.isNil(null); //=> trueisNotNil(null); //=> falseR.isNil(7); //=> falseisNotNil(7); //=> true
function compose
compose: { <TArgs extends any[], R1, R2, R3, R4, R5, R6, R7, TResult>( ...func: [ fnLast: (a: any) => TResult, ...func: ((a: any) => any)[], f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: TArgs) => R1 ] ): (...args: TArgs) => TResult; <TArgs extends any[], R1, R2, R3, R4, R5, R6, R7>( f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: TArgs) => R1 ): (...args: TArgs) => R7; <TArgs extends any[], R1, R2, R3, R4, R5, R6, R7>( f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: TArgs) => R1 ): (...args: TArgs) => R7; <TArgs extends any[], R1, R2, R3, R4, R5, R6>( f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: TArgs) => R1 ): (...args: TArgs) => R6; <TArgs extends any[], R1, R2, R3, R4, R5>( f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: TArgs) => R1 ): (...args: TArgs) => R5; <TArgs extends any[], R1, R2, R3, R4>( f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: TArgs) => R1 ): (...args: TArgs) => R4; <TArgs extends any[], R1, R2, R3>( f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: TArgs) => R1 ): (...args: TArgs) => R3; <TArgs extends any[], R1, R2>(f2: (a: R1) => R2, f1: (...args: TArgs) => R1): ( ...args: TArgs ) => R2; <TArgs extends any[], R1>(f1: (...args: TArgs) => R1): (...args: TArgs) => R1;};
Performs right-to-left function composition. The rightmost function may have any arity; the remaining functions must be unary.
The result of
R.compose
is not automatically curried.See also pipe.
Example 1
const classyGreeting = (firstName: string, lastName: string) => "The name's " + lastName + ", " + firstName + " " + lastNameconst yellGreeting = R.compose(R.toUpper, classyGreeting);yellGreeting('James', 'Bond'); //=> "THE NAME'S BOND, JAMES BOND"R.compose(Math.abs, R.add(1), R.multiply(2))(-4) //=> 7
function composeWith
composeWith: { <TArgs extends any[], TResult>( transformer: (fn: AnyFunction, intermediatResult: any) => any, fns: AtLeastOneFunctionsFlowFromRightToLeft<TArgs, TResult> ): (...args: TArgs) => TResult; (transformer: (fn: AnyFunction, intermediatResult: any) => any): < TArgs extends any[], TResult >( fns: AtLeastOneFunctionsFlowFromRightToLeft<TArgs, TResult> ) => (...args: TArgs) => TResult;};
Performs right-to-left function composition using transforming function. The last function may have any arity; the remaining functions must be unary.
The result of
R.composeWith
is not automatically curried. The transforming function is not used on the last argument.Example 1
const composeWhileNotNil = R.composeWith((f, res) => R.isNil(res) ? res : f(res));composeWhileNotNil([R.inc, R.prop('age')])({age: 1}) //=> 2
function concat
concat: { (placeholder: Placeholder): (<L1 extends any[], L2 extends any[]>( list1: L1, list2: L2 ) => [...L1, ...L2]) & (<S1 extends string, S2 extends string>(s1: S1, s2: S2) => `${S1}${S2}`); <L2 extends any[]>(placeholder: any, list2: L2): <L1 extends any[]>( list1: L1 ) => [...L1, ...L2]; <S2 extends string>(placeholder: any, s2: S2): <S1 extends string>( s1: S1 ) => `${S1}${S2}`; <L1 extends any[]>(list1: L1): <L2 extends any[]>(list2: L2) => [...L1, ...L2]; <S1 extends string>(s1: S1): <S2 extends string>(s2: S2) => `${S1}${S2}`; <L1 extends any[], L2 extends any[]>(list1: L1, list2: L2): [...L1, ...L2]; <S1 extends string, S2 extends string>(s1: S1, s2: S2): `${S1}${S2}`; (s1: string, s2: string): string; (s1: string): (s2: string) => string;};
Returns the result of concatenating the given lists or strings.
R.concat
expects both arguments to be of the same type, unlike the nativeArray.prototype.concat
method. It will throw an error if you concat anArray
with a non-Array
value.Dispatches to the
concat
method of the first argument, if present. Can also concatenate two members of a fantasy-land compatible semigroup.Example 1
R.concat('ABC', 'DEF'); // 'ABCDEF'R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]R.concat([], []); //=> []
function cond
cond: { <T, TF1 extends T, R>(pairs: [CondPairTypeguard<T, TF1, R>]): (value: T) => R; <T, TF1 extends T, TF2 extends T, R>( pairs: [CondPairTypeguard<T, TF1, R>, CondPairTypeguard<T, TF2, R>] ): (value: T) => R; <T, TF1 extends T, TF2 extends T, TF3 extends T, R>( pairs: [ CondPairTypeguard<T, TF1, R>, CondPairTypeguard<T, TF2, R>, CondPairTypeguard<T, TF3, R> ] ): (value: T) => R; <T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T, R>( pairs: [ CondPairTypeguard<T, TF1, R>, CondPairTypeguard<T, TF2, R>, CondPairTypeguard<T, TF3, R>, CondPairTypeguard<T, TF4, R> ] ): (value: T) => R; < T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T, TF5 extends T, R >( pairs: [ CondPairTypeguard<T, TF1, R>, CondPairTypeguard<T, TF2, R>, CondPairTypeguard<T, TF3, R>, CondPairTypeguard<T, TF4, R>, CondPairTypeguard<T, TF5, R> ] ): (value: T) => R; < T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T, TF5 extends T, TF6 extends T, R >( pairs: [ CondPairTypeguard<T, TF1, R>, CondPairTypeguard<T, TF2, R>, CondPairTypeguard<T, TF3, R>, CondPairTypeguard<T, TF4, R>, CondPairTypeguard<T, TF5, R>, CondPairTypeguard<T, TF6, R> ] ): (value: T) => R; < T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T, TF5 extends T, TF6 extends T, TF7 extends T, R >( pairs: [ CondPairTypeguard<T, TF1, R>, CondPairTypeguard<T, TF2, R>, CondPairTypeguard<T, TF3, R>, CondPairTypeguard<T, TF4, R>, CondPairTypeguard<T, TF5, R>, CondPairTypeguard<T, TF6, R>, CondPairTypeguard<T, TF7, R> ] ): (value: T) => R; < T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T, TF5 extends T, TF6 extends T, TF7 extends T, TF8 extends T, R >( pairs: [ CondPairTypeguard<T, TF1, R>, CondPairTypeguard<T, TF2, R>, CondPairTypeguard<T, TF3, R>, CondPairTypeguard<T, TF4, R>, CondPairTypeguard<T, TF5, R>, CondPairTypeguard<T, TF6, R>, CondPairTypeguard<T, TF7, R>, CondPairTypeguard<T, TF8, R> ] ): (value: T) => R; < T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T, TF5 extends T, TF6 extends T, TF7 extends T, TF8 extends T, TF9 extends T, R >( pairs: [ CondPairTypeguard<T, TF1, R>, CondPairTypeguard<T, TF2, R>, CondPairTypeguard<T, TF3, R>, CondPairTypeguard<T, TF4, R>, CondPairTypeguard<T, TF5, R>, CondPairTypeguard<T, TF6, R>, CondPairTypeguard<T, TF7, R>, CondPairTypeguard<T, TF8, R>, CondPairTypeguard<T, TF9, R> ] ): (value: T) => R; < T, TF1 extends T, TF2 extends T, TF3 extends T, TF4 extends T, TF5 extends T, TF6 extends T, TF7 extends T, TF8 extends T, TF9 extends T, TF10 extends T, R >( pairs: [ CondPairTypeguard<T, TF1, R>, CondPairTypeguard<T, TF2, R>, CondPairTypeguard<T, TF3, R>, CondPairTypeguard<T, TF4, R>, CondPairTypeguard<T, TF5, R>, CondPairTypeguard<T, TF6, R>, CondPairTypeguard<T, TF7, R>, CondPairTypeguard<T, TF8, R>, CondPairTypeguard<T, TF9, R>, CondPairTypeguard<T, TF10, R> ] ): (value: T) => R; <T extends any[], R>(pairs: readonly CondPair<T, R>[]): (...args: T) => R;};
Returns a function,
fn
, which encapsulatesif/else, if/else, ...
logic.R.cond
takes a list of [predicate, transformer] pairs. All of the arguments tofn
are applied to each of the predicates in turn until one returns a "truthy" value, at which pointfn
returns the result of applying its arguments to the corresponding transformer. If none of the predicates matches,fn
returns undefined.This is not a direct substitute for a
switch
statement. Remember that both elements of every pair passed tocond
are *functions*, andcond
returns a function.When using this function with a typeguard as predicate, **all** predicates in all pairs must be typeguards.
Example 1
const 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, temp => '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'
function construct
construct: <A extends any[], T>( constructor: (new (...args: A) => T) | ((...args: A) => T)) => _.F.Curry<(...args: A) => T>;
Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type.
See also invoker.
Example 1
// Constructor functionclass Animal {constructor(public kind: string) {}sighting() {return "It's a " + this.kind + "!";}}const AnimalConstructor = R.construct(Animal)// Notice we no longer need the 'new' keyword:AnimalConstructor('Pig'); //=> {"kind": "Pig", "sighting": function (){...}};const animalTypes = ["Lion", "Tiger", "Bear"];const animalSighting = R.invoker(0, 'sighting');const sightNewAnimal = R.compose(animalSighting, AnimalConstructor);R.map(sightNewAnimal, animalTypes); //=> ["It's a Lion!", "It's a Tiger!", "It's a Bear!"]
function constructN
constructN: <A extends any[], T, N extends number>( n: N, constructor: (new (...args: A) => T) | ((...args: A) => T)) => _.F.Curry< ( ...args_0: { readonly [Index in keyof Tuple<any, N>]: Index extends keyof A ? Intersection<Tuple<any, N>[Index], A[Index]> : Tuple<any, N>[Index]; } ) => T>;
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.
function converge
converge: { < TResult, FunctionsList extends readonly Fn[] & IfFunctionsArgumentsDoNotOverlap< _Fns, 'Functions arguments types must overlap' >, _Fns extends readonly Fn[] = FunctionsList >( converging: (...args: ReturnTypesOfFns<FunctionsList>) => TResult, branches: FunctionsList ): _.F.Curry<(...args: LargestArgumentsList<FunctionsList>) => TResult>; < CArgs extends readonly any[], TResult, FunctionsList extends readonly [ ...{ [Index in keyof CArgs]: (...args: readonly any[]) => CArgs[Index] } ] & IfFunctionsArgumentsDoNotOverlap< _Fns, 'Functions arguments types must overlap' >, _Fns extends readonly Fn[] = FunctionsList >( converging: (...args: CArgs) => TResult, branches: FunctionsList ): _.F.Curry<(...args: LargestArgumentsList<FunctionsList>) => TResult>;};
Accepts a converging function and a list of branching functions and returns a new function. When invoked, this new function is applied to some arguments, each branching function is applied to those same arguments. The results of each branching function are passed as arguments to the converging function to produce the return value.
See also useWith.
function count
count: { <T>(fn: (a: T) => boolean, list: readonly T[]): number; <T>(fn: (a: T) => boolean): (list: readonly T[]) => number;};
Returns the number of items in a given
list
matching the predicatef
.Example 1
const even = (x: number) => x % 2 == 0;R.count(even, [1, 2, 3, 4, 5]); // => 2R.map(R.count(even), [[1, 1, 1], [2, 3, 4, 5], [6]]); // => [0, 2, 1]
function countBy
countBy: { <T>(fn: (a: T) => string | number, list: readonly T[]): { [index: string]: number; }; <T>(fn: (a: T) => string | number): (list: readonly T[]) => { [index: string]: number; };};
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.Acts as a transducer if a transformer is given in list position.
See also transduce.
Example 1
const numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2];R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1}const letters = ['a', 'b', 'A', 'a', 'B', 'c'];R.countBy(R.toLower)(letters); //=> {'a': 3, 'b': 2, 'c': 1}
function curry
curry: <F extends AnyFunction>(f: F) => _.F.Curry<F>;
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 andg
isR.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. Ifg
is as above and_
isR.__
, 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)
Example 1
const addFourNumbers = (a: number, b: number, c: number, d: number) => a + b + c + d;const curriedAddFourNumbers = R.curry(addFourNumbers);const f = curriedAddFourNumbers(1, 2);const g = f(3);g(4); //=> 10
function curryN
curryN: { <N extends number, F extends AnyFunction>(length: N, fn: F): _.F.Curry< (...args: _.T.Take<Parameters<F>, _.N.NumberOf<N>>) => ReturnType<F> >; <N extends number>(length: N): <F extends AnyFunction>( fn: F ) => _.F.Curry< (...args: _.T.Take<Parameters<F>, _.N.NumberOf<N>>) => ReturnType<F> >;};
Returns a curried equivalent of the provided function, with the specified arity.
See also curry.
The curried function has two unusual capabilities.
First, its arguments needn't be provided one at a time. If
f
is a ternary function andg
isR.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. Ifg
is as above and_
isR.__
, 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)
Example 1
const sumArgs = (...args: number[]) => R.sum(args);const curriedAddFourNumbers = R.curryN(4, sumArgs);const f = curriedAddFourNumbers(1, 2);const g = f(3);g(4); //=> 10
function dec
dec: (n: number) => number;
Decrements its argument.
See also inc.
Example 1
R.dec(42); //=> 41
function defaultTo
defaultTo: { <T, U>(a: T, b: U | null | undefined): T | U; <T>(a: T): <U>(b: U) => T | U;};
Returns the second argument if it is not
null
,undefined
orNaN
; otherwise the first argument is returned.Example 1
const defaultTo42 = R.defaultTo(42);defaultTo42(null); //=> 42defaultTo42(undefined); //=> 42defaultTo42(false); //=> falsedefaultTo42('Ramda'); //=> 'Ramda'// parseInt('string') results in NaNdefaultTo42(parseInt('string')); //=> 42
function descend
descend: { <T>(fn: (obj: T) => Ord, a: T, b: T): Ordering; <T>(fn: (obj: T) => Ord): (a: T, b: T) => Ordering;};
Makes a descending comparator function out of a function that returns a value that can be compared with
<
and>
.See also ascend.
Example 1
type Person = { name: string; age: number; };const byAge = R.descend<Person>(R.prop('age'));const people = [{ name: 'Emma', age: 70 },{ name: 'Peter', age: 78 },{ name: 'Mikhail', age: 62 },];const peopleByOldestFirst = R.sort(byAge, people);//=> [{ name: 'Peter', age: 78 }, { name: 'Emma', age: 70 }, { name: 'Mikhail', age: 62 }]
function difference
difference: { <T>(list1: readonly T[], list2: readonly T[]): T[]; <T>(list1: readonly T[]): (list2: readonly T[]) => T[];};
Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
Object
s andArray
s are compared in terms of value equality, not reference equality.See also differenceWith, symmetricDifference, symmetricDifferenceWith, without.
Example 1
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]R.difference<{ a: number; } | { b: number; } | { c: number; }>([{a: 1}, {b: 2}], [{a: 1}, {c: 3}]) //=> [{b: 2}]
function differenceWith
differenceWith: { <T1, T2>( pred: (a: T1, b: T2) => boolean, list1: readonly T1[], list2: readonly T2[] ): T1[]; <T1, T2>(pred: (a: T1, b: T2) => boolean): ( list1: readonly T1[], list2: readonly T2[] ) => T1[]; <T1, T2>(pred: (a: T1, b: T2) => boolean, list1: readonly T1[]): ( list2: readonly T2[] ) => T1[];};
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.
See also See also difference, symmetricDifference, symmetricDifferenceWith.
Example 1
const cmp = (x: { a: number; }, y: { a: number; }) => x.a === y.a;const l1 = [{a: 1}, {a: 2}, {a: 3}];const l2 = [{a: 3}, {a: 4}];R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}]
function dissoc
dissoc: { <T extends object, K extends keyof T>(prop: K, obj: T): Omit<T, K>; <K extends string | number>(prop: K): <T extends object>(obj: T) => Omit<T, K>;};
function dissocPath
dissocPath: { <T>(path: Path, obj: any): T; <T>(path: Path): (obj: any) => T };
Makes a shallow clone of an object, omitting the property at the given path.
This copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference.
Example 1
R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}}
function divide
divide: { (__: Placeholder, b: number): (a: number) => number; (__: any): (b: number, a: number) => number; (a: number, b: number): number; (a: number): (b: number) => number;};
Divides two numbers. Equivalent to
a / b
but curried.See also multiply.
Example 1
R.divide(71, 100); //=> 0.71const half = R.divide(R.__, 2);half(42); //=> 21const reciprocal = R.divide(1);reciprocal(4); //=> 0.25
function drop
drop: { <T>(n: number, xs: readonly T[]): T[]; (n: number, xs: string): string; <T>(n: number): { (xs: string): string; (xs: readonly T[]): T[] };};
Returns all but the first
n
elements of the given list, string, or transducer/transformer.Dispatches to the
drop
method of the second argument, if present.Example 1
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'
function dropLast
dropLast: { <T>(n: number, xs: readonly T[]): T[]; (n: number, xs: string): string; <T>(n: number): { (xs: readonly T[]): T[]; (xs: string): string };};
Returns a list containing all but the last
n
elements of the given list.Acts as a transducer if a transformer is given in list position.
See also takeLast, drop, dropWhile, dropLastWhile, transduce.
Example 1
R.dropLast(1, ['foo', 'bar', 'baz']); //=> ['foo', 'bar']R.dropLast(2, ['foo', 'bar', 'baz']); //=> ['foo']R.dropLast(3, ['foo', 'bar', 'baz']); //=> []R.dropLast(4, ['foo', 'bar', 'baz']); //=> []R.dropLast(3, 'ramda'); //=> 'ra'
function dropLastWhile
dropLastWhile: { <T>(fn: (a: T) => boolean, list: readonly T[]): T[]; <T>(fn: (a: T) => boolean): (list: readonly T[]) => T[];};
Returns a new list excluding all the tailing elements of a given list which satisfy the supplied predicate function. It passes each value from the right to the supplied predicate function, skipping elements until the predicate function returns a falsy value.
Acts as a transducer if a transformer is given in list position.
See also takeLastWhile, addIndex, drop, dropWhile, transduce.
Example 1
const lteThree = (x: number) => x <= 3;R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4]R.dropLastWhile(x => x !== 'd', 'Ramda'); //=> 'Ramd'
function dropRepeats
dropRepeats: <T>(list: readonly T[]) => T[];
Returns a new list without any consecutively repeating elements. is used to determine equality.
Acts as a transducer if a transformer is given in list position.
See also transduce.
Example 1
R.dropRepeats([1, 1, 1, 2, 3, 4, 4, 2, 2]); //=> [1, 2, 3, 4, 2]
function dropRepeatsWith
dropRepeatsWith: { <T>(predicate: (left: T, right: T) => boolean, list: readonly T[]): T[]; <T>(predicate: (left: T, right: T) => boolean): (list: readonly T[]) => T[];};
Returns a new list without any consecutively repeating elements. Equality is determined by applying the supplied predicate to each pair of consecutive elements. The first element in a series of equal elements will be preserved.
Acts as a transducer if a transformer is given in list position.
See also transduce.
Example 1
const l = [1, -1, 1, 3, 4, -4, -4, -5, 5, 3, 3];R.dropRepeatsWith(R.eqBy(Math.abs), l); //=> [1, 3, 4, -5, 3]
function dropWhile
dropWhile: { <T>(fn: (a: T) => boolean, list: readonly T[]): T[]; <T>(fn: (a: T) => boolean): (list: readonly T[]) => T[];};
Returns a new list excluding the leading elements of a given list which satisfy the supplied predicate function. It passes each value to the supplied predicate function, skipping elements while the predicate function returns a truthy value.
Dispatches to the
dropWhile
method of the second argument, if present.Acts as a transducer if a transformer is given in list position.
Example 1
const lteTwo = (x: number) => x <= 2;R.dropWhile(lteTwo, [1, 2, 3, 4, 3, 2, 1]); //=> [3, 4, 3, 2, 1]R.dropWhile(x => x !== 'd' , 'Ramda'); //=> 'da'
function either
either: { <T extends Pred<any[]>>(pred1: T, pred2: T): T; <T extends Pred<any[]>>(pred1: T): (pred2: T) => T;};
A function wrapping calls to the two functions in an
||
operation, returning the result of the first function if it is truthy and the result of the second function otherwise.This is short-circuited, meaning that the second function will not be invoked if the first returns a truthy value.
Example 1
const gt10 = (x: number) => x > 10;const even = (x: number) => x % 2 === 0;const f = R.either(gt10, even);f(101); //=> truef(8); //=> true
function empty
empty: <T>(x: T) => T;
Returns the empty value of its argument's type. Ramda defines the empty value of
Array
([]
),Object
({}
), string (''
),TypedArray
(Uint8Array []
,Float32Array []
, etc) and arguments.Other types are supported if they define
<Type>.empty
,<Type>.prototype.empty
or implement the FantasyLand Monoid spec.Dispatches to the
empty
method of the first argument, if present.Example 1
R.empty([1, 2, 3]); //=> []R.empty('unicorns'); //=> ''R.empty({x: 1, y: 2}); //=> {}R.empty(Uint8Array.from([1, 2, 3])); //=> Uint8Array []
function endsWith
endsWith: { (substr: string, str: string): boolean; (substr: string): (str: string) => boolean; <T>(subList: readonly T[], list: readonly T[]): boolean; <T>(subList: readonly T[]): (list: readonly T[]) => boolean;};
Checks if a list ends with the provided sublist.
Similarly, checks if a string ends with the provided substring.
See also startsWith.
Example 1
R.endsWith('c', 'abc') //=> trueR.endsWith('b', 'abc') //=> falseR.endsWith(['c'], ['a', 'b', 'c']) //=> trueR.endsWith(['b'], ['a', 'b', 'c']) //=> false
function eqBy
eqBy: { <T>(fn: (a: T) => unknown, a: T, b: T): boolean; <T>(fn: (a: T) => unknown, a: T): (b: T) => boolean; <T>(fn: (a: T) => unknown): { (a: T, b: T): boolean; (a: T): (b: T) => boolean };};
Takes a function and two values in its domain and returns
true
if the values map to the same value in the codomain;false
otherwise.Example 1
R.eqBy(Math.abs, 5, -5); //=> true
function eqProps
eqProps: { <T, U>(prop: string, obj1: T, obj2: U): boolean; <P extends string>(prop: P): <T, U>( obj1: Record<P, T>, obj2: Record<P, U> ) => boolean; <T>(prop: string, obj1: T): <U>(obj2: U) => boolean;};
Reports whether two objects have the same value, in terms, for the specified property. Useful as a curried predicate.
Example 1
const o1 = { a: 1, b: 2, c: 3, d: 4 };const o2 = { a: 10, b: 20, c: 3, d: 40 };R.eqProps('a', o1, o2); //=> falseR.eqProps('c', o1, o2); //=> true
function equals
equals: { <T>(__: Placeholder, b: T): (a: T) => boolean; <T>(a: T, b: T): boolean; <T>(a: T): (b: T) => boolean;};
Returns
true
if its arguments are equivalent,false
otherwise. Handles cyclical data structures.Dispatches symmetrically to the
equals
methods of both arguments, if present.Example 1
R.equals(1, 1); //=> trueR.equals([1, 2, 3], [1, 2, 3]); //=> truetype Recursive = { v: Recursive; };const a: Recursive = {} as Recursive; a.v = a;const b: Recursive = {} as Recursive; b.v = b;R.equals(a, b); //=> true
function evolve
evolve: { <E extends Evolver<any>, V extends Evolvable<E>>( transformations: E, obj: V ): Evolve<V, E>; <E extends Evolver<any>>(transformations: E): <V extends Evolvable<E>>( obj: V ) => Evolve<V, E>;};
Creates a new object by evolving a shallow copy of the
object
, according to the functions intransformations
. All non-primitive properties are copied by reference.A function in
transformations
will not be invoked if its corresponding key does not exist in the evolved object.Example 1
const tomato = {firstName: ' Tomato ', data: {elapsed: 100, remaining: 1400}, id:123};const 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}, id:123}
function F
F: (...args: unknown[]) => false;
A function that always returns
false
. Any passed in parameters are ignored.See also T.
Example 1
R.F(); //=> false
function filter
filter: { <A, P extends A>(pred: (val: A) => val is P): { <B extends A>(list: readonly B[]): P[]; <B extends A>(dict: Dictionary<B>): Dictionary<P>; }; <T>(pred: (value: T) => boolean): < P extends T, C extends readonly P[] | Dictionary<P> >( collection: C ) => C; <T, P extends T>(pred: (val: T) => val is P, list: readonly T[]): P[]; <T, P extends T>(pred: (val: T) => val is P, dict: Dictionary<T>): Dictionary<P>; <T, C extends readonly T[] | Dictionary<T>>( pred: (value: T) => boolean, collection: C ): C;};
Takes a predicate and a
Filterable
, and returns a newFilterable
of the same type containing the members of the givenFilterable
which satisfy the given predicate. Filterable objects include plain objects or any object that has a filter method such as Array.Dispatches to the
filter
method of the second argument, if present.Acts as a transducer if a transformer is given in list position.
Example 1
const isEven = (n: number) => n % 2 === 0;R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4]R.filter(isEven, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4}
function find
find: { <T, P extends T>(pred: (val: T) => val is P, list: readonly T[]): P | undefined; <T>(pred: (val: T) => boolean, list: readonly T[]): T; <T, P extends T>(pred: (val: T) => val is P): (list: readonly T[]) => P; <T>(pred: (val: T) => boolean): (list: readonly T[]) => T;};
Returns the first element of the list which matches the predicate, or
undefined
if no element matches.Dispatches to the
find
method of the second argument, if present.Acts as a transducer if a transformer is given in list position.
See also transduce.
Example 1
const xs = [{a: 1}, {a: 2}, {a: 3}];R.find(R.propEq('a', 2))(xs); //=> {a: 2}R.find(R.propEq('a', 4))(xs); //=> undefined
function findIndex
findIndex: { <T>(fn: (a: T) => boolean, list: readonly T[]): number; <T>(fn: (a: T) => boolean): (list: readonly T[]) => number;};
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.
Example 1
const xs = [{a: 1}, {a: 2}, {a: 3}];R.findIndex(R.propEq('a', 2))(xs); //=> 1R.findIndex(R.propEq('a', 4))(xs); //=> -1
function findLast
findLast: { <T, P extends T>(pred: (val: T) => val is P, list: readonly T[]): P | undefined; <T>(pred: (val: T) => boolean, list: readonly T[]): T; <T, P extends T>(pred: (val: T) => val is P): (list: readonly T[]) => P; <T>(pred: (val: T) => boolean): (list: readonly T[]) => T;};
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.
See also transduce.
Example 1
const 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
function findLastIndex
findLastIndex: { <T>(fn: (a: T) => boolean, list: readonly T[]): number; <T>(fn: (a: T) => boolean): (list: readonly T[]) => number;};
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.
See also lastIndexOf, transduce.
Example 1
const xs = [{a: 1, b: 0}, {a:1, b: 1}];R.findLastIndex(R.propEq('a', 1))(xs); //=> 1R.findLastIndex(R.propEq('a', 4))(xs); //=> -1
function flatten
flatten: <T extends readonly any[]>(list: T) => _.T.Flatten<T>;
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.
See also unnest.
Example 1
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]
function flip
flip: { <T, U, TResult>(fn: (arg0: T, arg1: U) => TResult): ( arg1: U, arg0?: T ) => TResult; <F extends AnyFunction, P extends _.F.Parameters<F>>(fn: F): _.F.Curry< (...args: _.T.Merge<[P[1], P[0]], P>) => _.F.Return<F> >;};
Flips the order of the first two arguments to the given function.
Example 1
const mergeThree = <T>(a: T, b: T, c: T) => ([] as T[]).concat(a, b, c);mergeThree(1, 2, 3); //=> [1, 2, 3]R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3]
function forEach
forEach: { <T>(fn: (x: T) => void, list: readonly T[]): T[]; <T>(fn: (x: T) => void): (list: readonly T[]) => T[]; <T>(fn: (x: T) => void, list: readonly T[]): T[]; <T>(fn: (x: T) => void): (list: readonly T[]) => T[];};
Iterate over the given list, calling the given function for each element in the list.
R.forEach
does not skip deleted or unassigned indices (sparse arrays), unlike the nativeArray.prototype.forEach
method.Also note that, unlike
Array.prototype.forEach
,R.forEach
returns the original array. In some libraries this function is namedeach
.Dispatches to the
forEach
method of the second argument, if present.Example 1
const printXPlusFive = (x: number) => console.log(x + 5);R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3]// logs 6// logs 7// logs 8
function forEachObjIndexed
forEachObjIndexed: { <T>(fn: (value: T[keyof T], key: keyof T, obj: T) => void, obj: T): T; <T>(fn: (value: T[keyof T], key: keyof T, obj: T) => void): (obj: T) => T;};
Iterate over the given object, calling the given function for each key and value in the object.
Example 1
const printKeyConcatValue = (value: unknown, key: string) => console.log(key + ':' + value);R.forEachObjIndexed(printKeyConcatValue, {x: 1, y: 2}); //=> {x: 1, y: 2}// logs x:1// logs y:2
function fromPairs
fromPairs: <V>( pairs: | ReadonlyArray<Readonly<KeyValuePair<string, V>>> | ReadonlyArray<Readonly<KeyValuePair<number, V>>>) => { [index: string]: V };
function groupBy
groupBy: { <T, K extends string = string>(fn: (a: T) => K, list: readonly T[]): Record< K, T[] >; <T, K extends string = string>(fn: (a: T) => K): ( list: readonly T[] ) => Record<K, T[]>;};
Splits a list into sub-lists stored in an object, based on the result of calling a key-returning function on each element, and grouping the results according to values returned.
Dispatches to the
groupBy
method of the second argument, if present.Acts as a transducer if a transformer is given in list position.
Example 1
type Student = { name: string; score: number; }const byGrade = R.groupBy((student: Student) => {const score = student.score;return score < 65 ? 'F' :score < 70 ? 'D' :score < 80 ? 'C' :score < 90 ? 'B' : 'A';});const 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}]// }
function groupWith
groupWith: { <T>(fn: (x: T, y: T) => boolean): (list: readonly T[]) => T[][]; <T>(fn: (x: T, y: T) => boolean, list: readonly T[]): T[][]; <T>(fn: (x: T, y: T) => boolean, list: string): string[];};
Takes a list and returns a list of lists where every adjacent element of each sublist satisfies the given predicate.
Example 1
R.groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21])//=> [[0], [1, 1], [2], [3], [5], [8], [13], [21]]R.groupWith((a, b) => a + 1 === b, [0, 1, 1, 2, 3, 5, 8, 13, 21])//=> [[0, 1], [1, 2, 3], [5], [8], [13], [21]]R.groupWith((a, b) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21])//=> [[0], [1, 1], [2], [3, 5], [8], [13, 21]]const isVowel = R.test(/^[aeiou]$/i);R.groupWith(R.eqBy(isVowel), 'aestiou')//=> ['ae', 'st', 'iou']
function gt
gt: { (__: Placeholder, b: number): (a: number) => boolean; (__: any): (b: number, a: number) => boolean; (a: number, b: number): boolean; (a: string, b: string): boolean; (a: number): (b: number) => boolean;};
function gte
gte: { (__: Placeholder, b: number): (a: number) => boolean; (__: any): (b: number, a: number) => boolean; (a: number, b: number): boolean; (a: string, b: string): boolean; (a: number): (b: number) => boolean;};
function has
has: { (__: Placeholder, obj: unknown): (s: string) => boolean; (__: any): <P extends string>( obj: unknown, s: P ) => obj is A.Clean<{ [K in Key]: { [P in K]: unknown } }[Key]>; <P extends string>(s: P, obj: unknown): obj is A.Clean< { [K in Key]: { [P in K]: unknown } }[Key] >; <P extends string>(s: P): ( obj: unknown ) => obj is A.Clean<{ [K in Key]: { [P in K]: unknown } }[Key]>;};
Returns whether or not an object has an own property with the specified name.
Example 1
const hasName = R.has('name');hasName({name: 'alice'}); //=> truehasName({name: 'bob'}); //=> truehasName({}); //=> falseconst point = {x: 0, y: 0};const pointHas = R.has(R.__, point);pointHas('x'); //=> truepointHas('y'); //=> truepointHas('z'); //=> false
function hasIn
hasIn: { <T>(s: string, obj: T): boolean; (s: string): <T>(obj: T) => boolean };
Returns whether or not an object or its prototype chain has a property with the specified name.
Example 1
class Rectangle {constructor(public width: number, public height: number) {}area() {return this.width * this.height;}}const square = new Rectangle(2, 2);R.hasIn('width', square); //=> trueR.hasIn('area', square); //=> true
function hasPath
hasPath: { <T>(list: readonly string[], obj: T): boolean; (list: readonly string[]): <T>(obj: T) => boolean;};
Returns whether or not a path exists in an object. Only the object's own properties are checked.
See also has.
Example 1
R.hasPath(['a', 'b'], {a: {b: 2}}); // => trueR.hasPath(['a', 'b'], {a: {b: undefined}}); // => trueR.hasPath(['a', 'b'], {a: {c: 2}}); // => falseR.hasPath(['a', 'b'], {}); // => false
function head
head: { (str: string): string; (list: readonly []): undefined; <T>(list: readonly T[]): T;};
function identical
identical: { <T>(a: T, b: T): boolean; <T>(a: T): (b: T) => boolean };
Returns
true
if its arguments are identical,false
otherwise. Values are identical if they reference the same memory.NaN
is identical toNaN
;0
and-0
are not identical.This is merely a curried version of ES6
Object.is
.Example 1
const o = {};R.identical(o, o); //=> trueR.identical(1, 1); //=> trueR.identical<string | number>(1, '1'); //=> falseR.identical([], []); //=> falseR.identical(0, -0); //=> falseR.identical(NaN, NaN); //=> true
function identity
identity: <T>(a: T) => T;
A function that returns its argument. Good as a default or placeholder function.
Example 1
R.identity(1); //=> 1const obj = {};R.identity(obj) === obj; //=> true
function ifElse
ifElse: { <T, TF extends T, TOnTrueResult, TOnFalseResult>( pred: PredTypeguard<T, TF>, onTrue: (a: TF) => TOnTrueResult, onFalse: (a: Exclude<T, TF>) => TOnFalseResult ): (a: T) => TOnTrueResult | TOnFalseResult; <TArgs extends any[], TOnTrueResult, TOnFalseResult>( fn: Pred<TArgs>, onTrue: (...args: TArgs) => TOnTrueResult, onFalse: (...args: TArgs) => TOnFalseResult ): (...args: TArgs) => TOnTrueResult | TOnFalseResult;};
Creates a function that will process either the onTrue or the onFalse function depending upon the result of the condition predicate.
Example 1
const incCount = R.ifElse(R.has('count'),R.over(R.lensProp<{ count: number; }>('count'), R.inc),R.assoc('count', 1));incCount({ count: 1 }); //=> { count: 2 }
function inc
inc: (n: number) => number;
Increments its argument.
See also dec.
Example 1
R.inc(42); //=> 43
function includes
includes: { (__: Placeholder, list: readonly string[] | string): (s: string) => boolean; <T>(__: any, list: readonly T[]): (target: T) => boolean; (__: any): (list: string | readonly string[], s: string) => boolean; <T>(__: any): (list: readonly T[], target: T) => boolean; (s: string, list: string | readonly string[]): boolean; (s: string): (list: string | readonly string[]) => boolean; <T>(target: T, list: readonly T[]): boolean; <T>(target: T): (list: readonly T[]) => boolean;};
Returns
true
if the specified value is equal, inR.equals
terms, to at least one element of the given list;false
otherwise. Also works with strings.See also any.
Example 1
R.includes(3, [1, 2, 3]); //=> trueR.includes(4, [1, 2, 3]); //=> falseR.includes([42], [[42]]); //=> trueR.includes('ba', 'banana'); //=> trueR.includes({ name: 'Fred' }, [{ name: 'Fred' }]); //=> true
function indexBy
indexBy: { <T, K extends string | number = string>(fn: (a: T) => K, list: readonly T[]): { [key in K]: T; }; <T, K extends string | number = string>(fn: (a: T) => K, list: readonly T[]): { [key in NonNullable<K>]?: T; }; <T, K extends string | number = string>(fn: (a: T) => K): ( list: readonly T[] ) => { [key in K]: T }; <T, K extends string | number = string>(fn: (a: T) => K): ( list: readonly T[] ) => { [key in NonNullable<K>]?: T };};
Given a function that generates a key, turns a list of objects into an object indexing the objects by the given key.
If multiple objects generate the same value for the indexing key only the last value will be included in the generated object.
Acts as a transducer if a transformer is given in list position.
Example 1
const list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}];R.indexBy(R.prop('id'), list);//=> {abc: {id: 'abc', title: 'B'}, xyz: {id: 'xyz', title: 'A'}}
function indexOf
indexOf: { (target: string, list: readonly string[] | string): number; (target: string): (list: string | readonly string[]) => number; <T>(target: T, list: readonly T[]): number; <T>(target: T): (list: readonly T[]) => number;};
Returns the position of the first occurrence of an item in an array, or -1 if the item is not included in the array. is used to determine equality.
See also lastIndexOf, findIndex.
Example 1
R.indexOf(3, [1,2,3,4]); //=> 2R.indexOf(10, [1,2,3,4]); //=> -1
function init
init: { <T>(list: readonly T[]): T[]; (list: string): string };
function innerJoin
innerJoin: { <T1, T2>( pred: (a: