__ Function

Added in v0.6.0

参数占位符,可以对任何位置的参数进行占位。

假设 g 代表柯里化的三元函数,_ 代表 R.__,则下面几种写法是等价的:

  • 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)
const greet = R.replace('{name}', R.__, 'Hello, {name}!'); greet('Alice'); //=> 'Hello, Alice!'

add Math

Number → Number → Number
Parameters
  • a
  • b
Returns Number

Added in v0.1.0

两数相加。

See also subtract.
R.add(2, 3); //=> 5 R.add(7)(10); //=> 17

addIndex Function

(((a …) → b) … → [a] → *) → (((a …, Int, [a]) → b) … → [a] → *)
Parameters
  • fn

    A list iteration function that does not pass index or list to its callback

Returns function An altered list iteration function that passes (item, index, list) to its callback

Added in v0.15.0

通过向列表迭代函数的回调函数添加两个新的参数:当前索引、整个列表,创建新的列表迭代函数。

例如,本来 R.map 的回调函数是单参数函数:R.map(a => b, list)addIndex 可以将 map 的回调函数改造为接受三个参数的函数 R.addIndex(R.map)((a, index, list) => b, list)

注意,addIndex 只适用于回调函数是首个参数、列表是最后一个参数的列表迭代函数。(如果列表参数没有用到,后一个条件可以忽略)。

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']

adjust List

Number → (a → a) → [a] → [a]
Parameters
  • idx

    The index.

  • fn

    The function to apply.

  • list

    An array-like object whose value at the supplied index will be replaced.

Returns Array 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.

Added in v0.14.0

对数组中指定索引处的值进行函数转换。

See also update.
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']

all List

(a → Boolean) → [a] → Boolean
Parameters
  • fn

    The predicate function.

  • list

    The array to consider.

Returns Boolean `true` if the predicate is satisfied by every element, `false` otherwise.

Added in v0.1.0

判断列表中的所有元素是否都满足给定的条件,若都满足,则返回 true;否则,返回 false

若第二个参数自身存在 all 方法,则调用自身的 all 方法。

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装 。

See also any, none, transduce.
const equals3 = R.equals(3); R.all(equals3)([3, 3, 3, 3]); //=> true R.all(equals3)([3, 3, 1, 3]); //=> false

allPass Logic

[(*… → Boolean)] → (*… → Boolean)
Parameters
  • predicates

    An array of predicates to check

Returns function The combined predicate

Added in v0.9.0

传入包含多个 predicate 的列表,返回一个 predicate:如果给定的参数满足列表中的所有 predicate ,则返回 true

该函数返回一个柯里化的函数,参数个数由列表中参数最多的 predicate 决定。

See also anyPass.
const isQueen = R.propEq('rank', 'Q'); const isSpade = R.propEq('suit', '♠︎'); const isQueenOfSpades = R.allPass([isQueen, isSpade]); isQueenOfSpades({rank: 'Q', suit: '♣︎'}); //=> false isQueenOfSpades({rank: 'Q', suit: '♠︎'}); //=> true

always Function

a → (* → a)
Parameters
  • val

    The value to wrap in a function

Returns function A Function :: * -> val.

Added in v0.1.0

返回一个返回恒定值的函数。注意,对于非原始值,返回的值是对原始值的引用。

此函数在其他语言或库中也被称作:constconstant、或 K (K combinator 中)

const t = R.always('Tee'); t(); //=> 'Tee'

and Logic

a → b → a | b
Parameters
  • a
  • b
Returns Any

Added in v0.1.0

如果两个参数都是 true,则返回 true;否则返回 false

See also both, or.
R.and(true, true); //=> true R.and(true, false); //=> false R.and(false, true); //=> false R.and(false, false); //=> false

andThen Function

(a → b) → (Promise e a) → (Promise e b)
(a → (Promise e b)) → (Promise e a) → (Promise e b)
Parameters
  • onSuccess

    The function to apply. Can return a value or a promise of a value.

  • p
Returns Promise The result of calling `p.then(onSuccess)`

Added in v0.27.1

将 onSuccess 函数应用于一个 fulfilled Promise 的内部值,并将计算结果放入新的 Promise 中返回。这对于处理函数组合内的 promises 很有用。

See also otherwise.
const makeQuery = email => ({ query: { email }}); const fetchMember = request => 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);

any List

(a → Boolean) → [a] → Boolean
Parameters
  • fn

    The predicate function.

  • list

    The array to consider.

Returns Boolean `true` if the predicate is satisfied by at least one element, `false` otherwise.

Added in v0.1.0

只要列表中有一个元素满足 predicate,就返回 true,否则返回 false

若第二个参数自身存在 any 方法,则调用其自身的 any

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装 。

See also all, none, transduce.
const lessThan0 = R.flip(R.lt)(0); const lessThan2 = R.flip(R.lt)(2); R.any(lessThan0)([1, 2]); //=> false R.any(lessThan2)([1, 2]); //=> true

anyPass Logic

[(*… → Boolean)] → (*… → Boolean)
Parameters
  • predicates

    An array of predicates to check

Returns function The combined predicate

Added in v0.9.0

传入包含多个 predicate 的列表,返回一个 predicate:只要给定的参数满足列表中的一个 predicate ,就返回 true

该函数返回一个柯里化的函数,参数个数由列表中参数最多的 predicate 决定。

See also allPass.
const isClub = R.propEq('suit', '♣'); const isSpade = R.propEq('suit', '♠'); const isBlackCard = R.anyPass([isClub, isSpade]); isBlackCard({rank: '10', suit: '♣'}); //=> true isBlackCard({rank: 'Q', suit: '♠'}); //=> true isBlackCard({rank: 'Q', suit: '♦'}); //=> false

ap Function

[a → b] → [a] → [b]
Apply f => f (a → b) → f a → f b
(r → a → b) → (r → a) → (r → b)
Parameters
  • applyF
  • applyX
Returns *

Added in v0.3.0

ap 将函数列表作用于值列表上。

若第二个参数自身存在 ap 方法,则调用自身的 ap 方法。柯里化函数也可以作为 applicative。

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 passed R.ap(R.concat, R.toUpper)('Ramda') //=> 'RamdaRAMDA'

aperture List

Number → [a] → [[a]]
Parameters
  • n

    The size of the tuples to create

  • list

    The list to split into n-length tuples

Returns Array The resulting list of `n`-length tuples

Added in v0.12.0

返回一个新列表,列表中的元素为由原列表相邻元素组成的 n 元组。如果 n 大于列表的长度,则返回空列表。

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装 。

See also transduce.
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

a → [a] → [a]
Parameters
  • el

    The element to add to the end of the new list.

  • list

    The list of elements to add a new item to. list.

Returns Array A new list containing the elements of the old list followed by `el`.

Added in v0.1.0

在列表末尾拼接一个元素。

See also prepend.
R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests'] R.append('tests', []); //=> ['tests'] R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']]

apply Function

(*… → a) → [*] → a
Parameters
  • fn

    The function which will be called with args

  • args

    The arguments to call fn with

Returns * result The result, equivalent to `fn(...args)`

Added in v0.7.0

将函数 fn 作用于参数列表 argsapply 可以将变参函数转换为为定参函数。如果上下文很重要,则 fn 应该绑定其上下文。

See also call, unapply.
const nums = [1, 2, 3, -99, 42, 6, 7]; R.apply(Math.max, nums); //=> 42

applySpec Function

{k: ((a, b, …, m) → v)} → ((a, b, …, m) → {k: v})
Parameters
  • spec

    an object recursively mapping properties to functions for producing the values for these properties.

Returns function A function that returns an object of the same structure as `spec', with each property set to the value returned by calling its associated function with the supplied arguments.

Added in v0.20.0

接受一个属性值为函数的对象,返回一个能生成相同结构对象的函数。返回的函数使用传入的参数调用对象的每个属性位对应的函数,来生成相应属性的值。

See also converge, juxt.
const getMetrics = R.applySpec({ sum: R.add, nested: { mul: R.multiply } }); getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } }

applyTo Function

a → (a → b) → b
Parameters
  • x

    The value

  • f

    The function to apply

Returns * The result of applying `f` to `x`

Added in v0.25.0

接受一个值,并将一个函数作用于其上。

该函数又被称为 thrush combinator 。

const t42 = R.applyTo(42); t42(R.identity); //=> 42 t42(R.add(1)); //=> 43

ascend Function

Ord b => (a → b) → a → a → Number
Parameters
  • fn

    A function of arity one that returns a value that can be compared

  • a

    The first item to be compared.

  • b

    The second item to be compared.

Returns Number `-1` if fn(a) < fn(b), `1` if fn(b) < fn(a), otherwise `0`

Added in v0.23.0

由返回值可与 <> 比较的函数,创建一个升序比较函数。

See also descend.
const byAge = R.ascend(R.prop('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 }]

assoc Object

Idx → a → {k: v} → {k: v}
Idx = String | Int
Parameters
  • prop

    The property name to set

  • val

    The new value

  • obj

    The object to clone

Returns Object A new object equivalent to the original except for the changed property.

Added in v0.8.0

浅复制对象,然后设置或覆盖对象的指定属性。

注意,该函数也会将 prototype 属性复制到新的对象中。所有 non-primitive 属性都通过引用复制。

See also dissoc, pick.
R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3}

assocPath Object

[Idx] → a → {a} → {a}
Idx = String | Int | Symbol
Parameters
  • path

    the path to set

  • val

    The new value

  • obj

    The object to clone

Returns Object A new object equivalent to the original except along the specified path.

Added in v0.8.0

浅复制对象,设置或覆盖即将创建的给定路径所需的节点,并将特定值放在该路径的末端。

注意,这也会将 prototype 属性复制到新对象上。所有 non-primitive 属性都通过引用复制。

See also dissocPath.
R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} // Any missing or non-object keys in path will be overridden R.assocPath(['a', 'b', 'c'], 42, {a: 5}); //=> {a: {b: {c: 42}}}

binary Function

(a → b → c → … → z) → ((a, b) → z)
Parameters
  • fn

    The function to wrap.

Returns function A new function wrapping `fn`. The new function is guaranteed to be of arity 2.

Added in v0.2.0

将任意元函数封装为二元函数(只接受2个参数)中。任何额外的参数都不会传递给被封装的函数。

See also nAry, unary.
const takesThreeArgs = function(a, b, c) { return [a, b, c]; }; takesThreeArgs.length; //=> 3 takesThreeArgs(1, 2, 3); //=> [1, 2, 3] const 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

(* → *) → {*} → (* → *)
Parameters
  • fn

    The function to bind to context

  • thisObj

    The context to bind fn to

Returns function A function that will execute in the context of `thisObj`.

Added in v0.6.0

创建一个绑定了上下文的函数。

注意:与 Function.prototype.bind 不同,R.bind 不会绑定额外参数。

See also partial.
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}

both Logic

(*… → Boolean) → (*… → Boolean) → (*… → Boolean)
Parameters
  • f

    A predicate

  • g

    Another predicate

Returns function a function that applies its arguments to `f` and `g` and `&&`s their outputs together.

Added in v0.12.0

该函数调用两个函数,并对两函数返回值进行与操作。若第一个函数结果为 false-y 值 (false, null, 0 等),则返回该结果,否则返回第二个函数的结果。注意,both 为短路操作,即如果第一个函数返回 false-y 值,则不会调用第二个函数。

除了函数,R.both 还接受任何兼容 fantasy-land 的 applicative functor。

See also either, and.
const gt10 = R.gt(R.__, 10) const lt20 = R.lt(R.__, 20) const f = R.both(gt10, lt20); f(15); //=> true f(30); //=> false R.both(Maybe.Just(false), Maybe.Just(55)); // => Maybe.Just(false) R.both([false, false, 'a'], [11]); //=> [false, false, 11]

call Function

((*… → a), *…) → a
Parameters
  • fn

    The function to apply to the remaining arguments.

  • args

    Any number of positional arguments.

Returns *

Added in v0.9.0

提取第一个参数作为函数,其余参数作为刚提取的函数的参数,调用该函数并将结果返回。

R.call 可以用作 R.converge 的 convergeing 函数:第一个分支函数生成函数,其余分支函数生成一系列值作为该函数的参数。(R.converge 第二个参数为一个分支函数列表)。

See also apply.
R.call(R.add, 1, 2); //=> 3 const indentN = R.pipe( R.repeat(' '), R.join(''), R.replace(/^(?!$)/gm) ); const 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

Chain m => (a → m b) → m a → m b
Parameters
  • fn

    The function to map with

  • list

    The list to map over

Returns Array The result of flat-mapping `list` with `fn`

Added in v0.3.0

chain 将函数映射到列表中每个元素,并将结果连接起来。 chain 在一些库中也称为 flatMap(先 map 再 flatten )。

若第二个参数存在 chain 方法,则调用其自身的 chain方法。该参数需符合 FantasyLand Chain 规范

如果第二个参数是函数,chain(f, g)(x) 等价于 f(g(x), x)

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装。

const duplicate = n => [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]

clamp Relation

Ord a => a → a → a → a
Parameters
  • minimum

    The lower limit of the clamp (inclusive)

  • maximum

    The upper limit of the clamp (inclusive)

  • value

    Value to be clamped

Returns Number Returns `minimum` when `val < minimum`, `maximum` when `val > maximum`, returns `val` otherwise

Added in v0.20.0

将数字限制在指定的范围内。

clamp 也可用于其他有序类型,如字符串和日期。

R.clamp(1, 10, -5) // => 1 R.clamp(1, 10, 15) // => 10 R.clamp(1, 10, 4) // => 4

clone Object

{*} → {*}
Parameters
  • value

    The object or array to clone

Returns * A deeply cloned copy of `val`

Added in v0.1.0

深复制。其值可能(嵌套)包含 ArrayObjectNumberStringBooleanDate 类型的数据。Function 通过引用复制。

若自身存在 clone 方法,则调用自身的 clone 方法。

const objects = [{}, {}, {}]; const objectsClone = R.clone(objects); objects === objectsClone; //=> false objects[0] === objectsClone[0]; //=> false

collectBy List

Idx a => (b → a) → [b] → [[b]]
Idx = String | Int | Symbol
Parameters
  • fn

    Function :: a -> Idx

  • list

    The array to group

Returns Array An array of arrays where each sub-array contains items for which the String-returning function has returned the same value.

Added in v0.28.0

根据列表中每一个元素调用函数的结果是否相等,将一个列表拆分为多个子列表。

See also groupBy, partition.
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: '🍝'} ] ]

comparator Function

((a, b) → Boolean) → ((a, b) → Number)
Parameters
  • pred

    A predicate function of arity two which will return true if the first argument is less than the second, false otherwise

Returns function A Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0`

Added in v0.1.0

由首个参数是否小于第二个参数的判断函数,生成一个比较函数。

const byAge = R.comparator((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 }]

complement Logic

(*… → *) → (*… → Boolean)
Parameters
  • f
Returns function

Added in v0.12.0

对函数的返回值取反。接受一个函数 f,返回一个新函数 g:在输入参数相同的情况下,若 f 返回 'true-y' ,则 g 返回 false-y ,反之亦然。

R.complement 可用于任何 functor。

See also not.
const isNotNil = R.complement(R.isNil); R.isNil(null); //=> true isNotNil(null); //=> false R.isNil(7); //=> false isNotNil(7); //=> true

compose Function

((y → z), (x → y), …, (o → p), ((a, b, …, n) → o)) → ((a, b, …, n) → z)
Parameters
  • ...functions

    The functions to compose

Returns function

Added in v0.1.0

从右往左执行函数组合(右侧函数的输出作为左侧函数的输入)。最后一个函数可以是任意元函数(参数个数不限),其余函数必须是一元函数。

注意:compose 输出的函数不会自动进行柯里化。

See also pipe.
const classyGreeting = (firstName, lastName) => "The name's " + lastName + ", " + firstName + " " + lastName const 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

composeWith Function

((* → *), [(y → z), (x → y), …, (o → p), ((a, b, …, n) → o)]) → ((a, b, …, n) → z)
Parameters
  • transformer

    The transforming function

  • functions

    The functions to compose

Returns function

Added in v0.26.0

利用转换函数从右往左执行函数组合。最后一个函数可以是任意元函数(参数个数不限),其余函数必须是一元函数。

注意:composeWith 输出的函数不会自动进行柯里化。

See also compose, pipeWith.
const composeWhileNotNil = R.composeWith((f, res) => R.isNil(res) ? res : f(res)); composeWhileNotNil([R.inc, R.prop('age')])({age: 1}) //=> 2 composeWhileNotNil([R.inc, R.prop('age')])({}) //=> undefined

concat List

[a] → [a] → [a]
String → String → String
Parameters
  • firstList

    The first list

  • secondList

    The second list

Returns Array A list consisting of the elements of `firstList` followed by the elements of `secondList`.

Added in v0.1.0

连接列表或字符串。

注意:不同于 Array.prototype.concat, R.concat 要求两个参数类型相同。 如果将 Array 与非 Array 连接,将抛出错误。

若第一个参数自身存在 concat 方法,则调用自身的 concat

也可以用于连接 符合 fantasy-land 半群 类型的两个实例。

R.concat('ABC', 'DEF'); // 'ABCDEF' R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] R.concat([], []); //=> []

cond Logic

[[(*… → Boolean),(*… → *)]] → (*… → *)
Parameters
  • pairs

    A list of [predicate, transformer]

Returns function

Added in v0.6.0

返回一个封装了 if / else,if / else, ... 逻辑的函数 fnR.cond 接受列表元素为 [predicate,transformer] 的列表。 fn 的所有参数顺次作用于每个 predicate,直到有一个返回 "truthy" 值,此时相应 transformer 对参数处理,并作为 fn 的结果返回。 如果没有 predicate 匹配,则 fn 返回 undefined。

See also ifElse, unless, when.
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'

construct Function

(* → {*}) → (* → {*})
Parameters
  • fn

    The constructor function to wrap.

Returns function A wrapped, curried constructor function.

Added in v0.1.0

将构造函数封装进柯里化函数,新函数与原构造函数的传入参数类型及返回值类型相同。

See also invoker.
// Constructor function function Animal(kind) { this.kind = kind; }; Animal.prototype.sighting = function() { 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!"]

constructN Function

Number → (* → {*}) → (* → {*})
Parameters
  • n

    The arity of the constructor function.

  • Fn

    The constructor function to wrap.

Returns function A wrapped, curried constructor function.

Added in v0.4.0

将构造函数封装进柯里化函数,新函数与原构造函数的传入参数类型及返回值类型相同。为了能够使用变参的构造函数,返回函数的元数需要明确指定。

// Variadic Constructor function function Salad() { this.ingredients = arguments; } Salad.prototype.recipe = function() { const instructions = R.map(ingredient => 'Add a dollop of ' + ingredient, this.ingredients); return R.join('\n', instructions); }; const ThreeLayerSalad = R.constructN(3, Salad); // Notice we no longer need the 'new' keyword, and the constructor is curried for 3 arguments. const salad = ThreeLayerSalad('Mayonnaise')('Potato Chips')('Ketchup'); console.log(salad.recipe()); // Add a dollop of Mayonnaise // Add a dollop of Potato Chips // Add a dollop of Ketchup

converge Function

((x1, x2, …) → z) → [((a, b, …) → x1), ((a, b, …) → x2), …] → (a → b → … → z)
Parameters
  • after

    A function. after will be invoked with the return values of fn1 and fn2 as its arguments.

  • functions

    A list of functions.

Returns function A new function.

Added in v0.4.2

接受一个 converging 函数和一个分支函数列表,返回一个新函数。新函数的元数(参数个数)等于最长分支函数的元数。当被调用时,新函数接受参数,并将这些参数转发给每个分支函数;然后将每个分支函数的计算结果作为参数传递给 converging 函数,converging 函数的计算结果即新函数的返回值。

See also useWith.
const average = R.converge(R.divide, [R.sum, R.length]) average([1, 2, 3, 4, 5, 6, 7]) //=> 4 const strangeConcat = R.converge(R.concat, [R.toUpper, R.toLower]) strangeConcat("Yodel") //=> "YODELyodel"

count List

(a → Boolean) → [a] → Number
Parameters
  • predicate

    to match items against

Returns Array list of items to count in

Added in v0.28.0

返回符合 predicate f 的列表的个数。

const even = x => x % 2 == 0; R.count(even, [1, 2, 3, 4, 5]); // => 2 R.map(R.count(even), [[1, 1, 1], [2, 3, 4, 5], [6]]); // => [0, 2, 1]

countBy Relation

(a → String) → [a] → {*}
Parameters
  • fn

    The function used to map values to keys.

  • list

    The list to count elements from.

Returns Object An object mapping keys to number of occurrences in the list.

Added in v0.1.0

根据给定函数提供的统计规则对列表中的元素进行分类计数。返回一个对象,其键值对为:fn 根据列表元素生成键,列表中通过 fn 映射为对应键的元素的个数作为值。注意,由于 JavaScript 对象的实现方式,所有键都被强制转换为字符串。

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装 。

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}

curry Function

(* → a) → (* → a)
Parameters
  • fn

    The function to curry.

Returns function A new, curried function.

Added in v0.1.0

对函数进行柯里化。柯里化函数与其他语言中的柯里化函数相比,有两个非常好的特性:

  1. 参数不需要一次只传入一个。如果 f 是三元函数,gR.curry(f) ,则下列写法是等价的:
  • g(1)(2)(3)
  • g(1)(2, 3)
  • g(1, 2)(3)
  • g(1, 2, 3)
  1. 占位符值 R.__ 可用于标记暂未传入参数的位置。允许部分应用于任何参数组合,而无需关心它们的位置和顺序。假设 g 定义如前所示,_ 代表 R.__ ,则下列写法是等价的:
  • 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)
See also curryN, partial.
const addFourNumbers = (a, b, c, d) => a + b + c + d; const curriedAddFourNumbers = R.curry(addFourNumbers); const f = curriedAddFourNumbers(1, 2); const g = f(3); g(4); //=> 10

curryN Function

Number → (* → a) → (* → a)
Parameters
  • length

    The arity for the returned function.

  • fn

    The function to curry.

Returns function A new, curried function.

Added in v0.5.0

对函数进行柯里化,并限制柯里化函数的元数。柯里化函数有两个很好的特性:

  1. 参数不需要一次只传入一个。假设 gR.curryN(3, f) 生成,则下列写法是等价的:
  • g(1)(2)(3)
  • g(1)(2, 3)
  • g(1, 2)(3)
  • g(1, 2, 3)
  1. 占位符值 R.__ 可用于标记暂未传入参数的位置,允许部分应用于任何参数组合,而无需关心它们的位置和顺序。 假设 g 定义如前所示,_ 代表 R.__ ,则下列写法是等价的:
  • 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)
See also curry.
const sumArgs = (...args) => R.sum(args); const curriedAddFourNumbers = R.curryN(4, sumArgs); const f = curriedAddFourNumbers(1, 2); const g = f(3); g(4); //=> 10

dec Math

Number → Number
Parameters
  • n
Returns Number n - 1

Added in v0.9.0

减1。

See also inc.
R.dec(42); //=> 41

defaultTo Logic

a → b → a | b
Parameters
  • default

    The default value.

  • val

    val will be returned instead of default unless val is null, undefined or NaN.

Returns * The second value if it is not `null`, `undefined` or `NaN`, otherwise the default value

Added in v0.10.0

如果第二个参数不是 nullundefinedNaN,则返回第二个参数,否则返回第一个参数(默认值)。

const defaultTo42 = R.defaultTo(42); defaultTo42(null); //=> 42 defaultTo42(undefined); //=> 42 defaultTo42(false); //=> false defaultTo42('Ramda'); //=> 'Ramda' // parseInt('string') results in NaN defaultTo42(parseInt('string')); //=> 42

descend Function

Ord b => (a → b) → a → a → Number
Parameters
  • fn

    A function of arity one that returns a value that can be compared

  • a

    The first item to be compared.

  • b

    The second item to be compared.

Returns Number `-1` if fn(a) > fn(b), `1` if fn(b) > fn(a), otherwise `0`

Added in v0.23.0

由返回值可与 <> 比较的函数,创建一个降序比较函数。

See also ascend.
const byAge = R.descend(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 }]

difference Relation

[*] → [*] → [*]
Parameters
  • list1

    The first list.

  • list2

    The second list.

Returns Array The elements in `list1` that are not in `list2`.

Added in v0.1.0

求差集。求第一个列表中,未包含在第二个列表中的任一元素的集合。对象和数组比较数值相等,而非引用相等。

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: 1}, {b: 2}], [{a: 1}, {c: 3}]) //=> [{b: 2}]

differenceWith Relation

((a, a) → Boolean) → [a] → [a] → [a]
Parameters
  • pred

    A predicate used to test whether two items are equal.

  • list1

    The first list.

  • list2

    The second list.

Returns Array The elements in `list1` that are not in `list2`.

Added in v0.1.0

求第一个列表中未包含在第二个列表中的所有元素的集合(集合中没有重复元素)。两列表中的元素通过 predicate 判断相应元素是否同时 “包含在” 两列表中。

const cmp = (x, y) => 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}]

dissoc Object

String → {k: v} → {k: v}
Parameters
  • prop

    The name of the property to dissociate

  • obj

    The object to clone

Returns Object A new object equivalent to the original but without the specified property

Added in v0.10.0

删除对象中指定 prop 属性。

See also assoc, omit.
R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3}

dissocPath Object

[Idx] → {k: v} → {k: v}
Idx = String | Int | Symbol
Parameters
  • path

    The path to the value to omit

  • obj

    The object to clone

Returns Object A new object without the property at path

Added in v0.11.0

浅复制对象,删除返回对象中指定路径上的属性。

注意,这也会将 prototype 属性复制到新对象上并展开。所有 non-primitive 属性都通过引用复制。

See also assocPath.
R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}}

divide Math

Number → Number → Number
Parameters
  • a

    The first value.

  • b

    The second value.

Returns Number The result of `a / b`.

Added in v0.1.0

两数相除。等价于 a / b

See also multiply.
R.divide(71, 100); //=> 0.71 const half = R.divide(R.__, 2); half(42); //=> 21 const reciprocal = R.divide(1); reciprocal(4); //=> 0.25

drop List

Number → [a] → [a]
Number → String → String
Parameters
  • n
  • list
Returns * A copy of list without the first `n` elements

Added in v0.1.0

删除给定 list,string 或者 transducer/transformer(或者具有 drop 方法的对象)的前 n 个元素。

若第二个参数自身存在 drop 方法,则调用自身的 drop 方法。

若在 list 位置中给出 transfomer ,则用作 transducer

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'

dropLast List

Number → [a] → [a]
Number → String → String
Parameters
  • n

    The number of elements of list to skip.

  • list

    The list of elements to consider.

Returns Array A copy of the list with only the first `list.length - n` elements

Added in v0.16.0

删除 "list" 末尾的 n 个元素。

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装 。

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'

dropLastWhile List

(a → Boolean) → [a] → [a]
(a → Boolean) → String → String
Parameters
  • predicate

    The function to be called on each element

  • xs

    The collection to iterate over.

Returns Array A new array without any trailing elements that return `falsy` values from the `predicate`.

Added in v0.16.0

对 list 从后向前一直删除满足 predicate 的尾部元素,直到遇到第一个 falsy 值,此时停止删除操作。

predicate 需要作为第一个参数传入。

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装 。

const lteThree = x => x <= 3; R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4] R.dropLastWhile(x => x !== 'd' , 'Ramda'); //=> 'Ramd'

dropRepeats List

[a] → [a]
Parameters
  • list

    The array to consider.

Returns Array `list` without repeating elements.

Added in v0.14.0

返回一个没有连续重复元素的 list。通过 R.equals 函数进行相等性判断。

若在 list 位置中给出 transfomer ,则用作 transducer

See also transduce.
R.dropRepeats([1, 1, 1, 2, 3, 4, 4, 2, 2]); //=> [1, 2, 3, 4, 2]

dropRepeatsWith List

((a, a) → Boolean) → [a] → [a]
Parameters
  • pred

    A predicate used to test whether two items are equal.

  • list

    The array to consider.

Returns Array `list` without repeating elements.

Added in v0.14.0

返回一个没有连续重复元素的 list。首个参数提供的 predicate 用于检测 list 中相邻的两个元素是否相等。一系列相等元素中的首个元素会被保留。

若在 list 位置中给出 transfomer ,则用作 transducer

See also transduce.
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]

dropWhile List

(a → Boolean) → [a] → [a]
(a → Boolean) → String → String
Parameters
  • fn

    The function called per iteration.

  • xs

    The collection to iterate over.

Returns Array A new array.

Added in v0.9.0

对 list 从前向后删除满足 predicate 的头部元素,直到遇到第一个 falsy 值。

predicate 需要作为第一个参数传入。

若第二个参数自身存在 dropWhile 方法,则调用自身的 dropWhile 方法。

若在 list 位置中给出 transfomer ,则用作 transducer

const lteTwo = x => x <= 2; R.dropWhile(lteTwo, [1, 2, 3, 4, 3, 2, 1]); //=> [3, 4, 3, 2, 1] R.dropWhile(x => x !== 'd' , 'Ramda'); //=> 'da'

either Logic

(*… → Boolean) → (*… → Boolean) → (*… → Boolean)
Parameters
  • f

    a predicate

  • g

    another predicate

Returns function a function that applies its arguments to `f` and `g` and `||`s their outputs together.

Added in v0.12.0

返回由 || 运算符连接的两个函数的包装函数。如果两个函数中任一函数的执行结果为 truth-y,则返回其执行结果。 注意,这个是短路表达式,意味着如果第一个函数返回 truth-y 值的话,第二个函数将不会执行。

除了函数之外, R.either 也接受任何符合 fantasy-land 标准的 applicative functor

See also both, or.
const gt10 = x => x > 10; const even = x => x % 2 === 0; const f = R.either(gt10, even); f(101); //=> true f(8); //=> true R.either(Maybe.Just(false), Maybe.Just(55)); // => Maybe.Just(55) R.either([false, false, 'a'], [11]) // => [11, 11, "a"]

empty Function

a → a
Parameters
  • x
Returns *

Added in v0.3.0

根据传入参数的类型返回其对应的空值。Ramda 定义了各类型的空值如下:Array ([]),Object ({}),String (''),和 Arguments。empty 还支持其它定义了 <Type>.empty<Type>.prototype.empty 或 实现了 FantasyLand Monoid 规范 的类型。

若第一个参数自身存在 empty 方法,则调用自身的 empty 方法。

R.empty(Just(42)); //=> Nothing() R.empty([1, 2, 3]); //=> [] R.empty('unicorns'); //=> '' R.empty({x: 1, y: 2}); //=> {} R.empty(Uint8Array.from('123')); //=> Uint8Array []

endsWith List

[a] → [a] → Boolean
String → String → Boolean
Parameters
  • suffix
  • list
Returns Boolean

Added in v0.24.0

检查列表是否以指定的子列表结尾。

同样的,检查字符串是否以指定的子字符串结尾。

See also startsWith.
R.endsWith('c', 'abc') //=> true R.endsWith('b', 'abc') //=> false R.endsWith(['c'], ['a', 'b', 'c']) //=> true R.endsWith(['b'], ['a', 'b', 'c']) //=> false

eqBy Relation

(a → b) → a → a → Boolean
Parameters
  • f
  • x
  • y
Returns Boolean

Added in v0.18.0

接受一个函数和两个值,通过传入函数对两个值进行相等性判断。如果两个值的计算结果相等,则返回 true ;否则返回 false

R.eqBy(Math.abs, 5, -5); //=> true

eqProps Object

k → {k: v} → {k: v} → Boolean
Parameters
  • prop

    The name of the property to compare

  • obj1
  • obj2
Returns Boolean

Added in v0.1.0

判断两个对象指定的属性值是否相等。通过 R.equals 函数进行相等性判断。可用作柯里化的 predicate

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); //=> false R.eqProps('c', o1, o2); //=> true

equals Relation

a → b → Boolean
Parameters
  • a
  • b
Returns Boolean

Added in v0.15.0

如果传入的参数相等,返回 true;否则返回 false。可以处理几乎所有 JavaScript 支持的数据结构。

若两个参数自身存在 equals 方法,则对称地调用自身的 equals 方法。

R.equals(1, 1); //=> true R.equals(1, '1'); //=> false R.equals([1, 2, 3], [1, 2, 3]); //=> true const a = {}; a.v = a; const b = {}; b.v = b; R.equals(a, b); //=> true

evolve Object

{k: (v → v)} → {k: v} → {k: v}
Parameters
  • transformations

    The object specifying transformation functions to apply to the object.

  • object

    The object to be transformed.

Returns Object The transformed object.

Added in v0.9.0

递归地对 object 的属性进行变换,变换方式由 transformation 函数定义。所有非原始类型属性都通过引用来复制。

如果某个 transformation 函数对应的键在被变换的 object 中不存在,那么该方法将不会执行。

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}

F Function

* → Boolean
Parameters
Returns Boolean

Added in v0.9.0

恒定返回 false 的函数。忽略所有的输入参数。

See also T.
R.F(); //=> false

filter List

Filterable f => (a → Boolean) → f a → f a
Parameters
  • pred
  • filterable
Returns Array Filterable

Added in v0.1.0

使用 predicate 遍历传入的 Filterable,返回满足 predicate 的所有元素的新的 Filterable。新 Filterable 与原先的类型相同。Filterable 类型包括 plain object 或者任何带有 filter 方法的类型,如 Array

若第二个参数自身存在 filter 方法,则调用自身的 filter 方法。

若在 list 位置中给出 transfomer ,则用作 transducer

See also reject, transduce, addIndex.
const isEven = n => 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}

find List

(a → Boolean) → [a] → a | undefined
Parameters
  • fn

    The predicate function used to determine if the element is the desired one.

  • list

    The array to consider.

Returns Object The element found, or `undefined`.

Added in v0.1.0

查找并返回 list 中首个满足 predicate 的元素;如果未找到满足条件的元素,则返回 undefined

若第二个参数自身存在 find 方法,则调用自身的 find 方法。

若在 list 位置中给出 transfomer ,则用作 transducer

See also transduce.
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

findIndex List

(a → Boolean) → [a] → Number
Parameters
  • fn

    The predicate function used to determine if the element is the desired one.

  • list

    The array to consider.

Returns Number The index of the element found, or `-1`.

Added in v0.1.1

查找并返回 list 中首个满足 predicate 的元素的索引;如果未找到满足条件的元素,则返回 -1

若在 list 位置中给出 transfomer ,则用作 transducer

See also transduce, indexOf.
const 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

(a → Boolean) → [a] → a | undefined
Parameters
  • fn

    The predicate function used to determine if the element is the desired one.

  • list

    The array to consider.

Returns Object The element found, or `undefined`.

Added in v0.1.1

查找并返回 list 中最后一个满足 predicate 的元素;如果未找到满足条件的元素,则返回 undefined

若在 list 位置中给出 transfomer ,则用作 transducer

See also transduce.
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

findLastIndex List

(a → Boolean) → [a] → Number
Parameters
  • fn

    The predicate function used to determine if the element is the desired one.

  • list

    The array to consider.

Returns Number The index of the element found, or `-1`.

Added in v0.1.1

查找并返回 list 中最后一个满足 predicate 的元素的索引;如果未找到满足条件的元素,则返回 -1

若在 list 位置中给出 transfomer ,则用作 transducer

See also transduce, lastIndexOf.
const 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

[a] → [b]
Parameters
  • list

    The array to consider.

Returns Array The flattened list.

Added in v0.1.0

获取 list 的所有元素(包含所有子数组中的元素),然后由这些元素组成一个新的数组。深度优先。

See also unnest.
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

((a, b, c, …) → z) → (b → a → c → … → z)
Parameters
  • fn

    The function to invoke with its first two parameters reversed.

Returns * The result of invoking `fn` with its first two parameters' order reversed.

Added in v0.1.0

交换函数前两个参数的位置。

const mergeThree = (a, b, c) => [].concat(a, b, c); mergeThree(1, 2, 3); //=> [1, 2, 3] R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3]

forEach List

(a → *) → [a] → [a]
Parameters
  • fn

    The function to invoke. Receives one argument, value.

  • list

    The list to iterate over.

Returns Array The original list.

Added in v0.1.1

遍历 list,对 list 中的每个元素执行方法 fn

fn 接收单个参数: *(value)*。

注意: R.forEach 并不会跳过已删除的或者未赋值的索引(sparse arrays),这一点和原生的 Array.prototype.forEach 方法不同. 获取更多相关信息, 请查阅: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description

还要注意, 不同于 Array.prototype.forEach,Ramda 的 forEach 会将原数组返回。在某些库中,该方法也被称为 each.

若第二个参数自身存在 forEach 方法,则调用自身的 forEach 方法。

See also addIndex.
const printXPlusFive = x => console.log(x + 5); R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3] // logs 6 // logs 7 // logs 8

forEachObjIndexed Object

((a, String, StrMap a) → Any) → StrMap a → StrMap a
Parameters
  • fn

    The function to invoke. Receives three argument, value, key, obj.

  • obj

    The object to iterate over.

Returns Object The original object.

Added in v0.23.0

遍历 object,对 object 中的每对 keyvalue 执行方法 fn

fn 接收三个参数: (value, key, obj).

const printKeyConcatValue = (value, key) => console.log(key + ':' + value); R.forEachObjIndexed(printKeyConcatValue, {x: 1, y: 2}); //=> {x: 1, y: 2} // logs x:1 // logs y:2

fromPairs List

[[k,v]] → {k: v}
Parameters
  • pairs

    An array of two-element arrays that will be the keys and values of the output object.

Returns Object The object made by pairing up `keys` and `values`.

Added in v0.3.0

由一系列 “键值对” 创建一个 object。如果某个键出现多次,选取最右侧的键值对。

See also toPairs, pair.
R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3}

groupBy List

Idx a => (b → a) → [b] → {a: [b]}
Idx = String | Int | Symbol
Parameters
  • fn

    Function :: a -> Idx

  • list

    The array to group

Returns Object An object with the output of `fn` for keys, mapped to arrays of elements that produced that key when passed to `fn`.

Added in v0.1.0

将列表根据一定规则拆分成多组子列表,并存储在一个对象中。

对列表中的每个元素调用函数,根据函数返回结果进行分组。函数返回字符串作为相等性判断,返回的字符串作为存储对象的键,具有相同返回字符串的元素聚合为数组,作为该键的值。

若第二个参数自身存在 groupBy 方法,则调用自身的 groupBy 方法。

若在 list 位置中给出 transfomer ,则用作 transducer

See also reduceBy, transduce, indexBy.
const byGrade = R.groupBy(function(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}] // }

groupWith List

((a, a) → Boolean) → [a] → [[a]]
Parameters
  • fn

    Function for determining whether two given (adjacent) elements should be in the same group

  • list

    The array to group. Also accepts a string, which will be treated as a list of characters.

Returns List A list that contains sublists of elements, whose concatenations are equal to the original list.

Added in v0.21.0

通过给定的对比函数,将列表按顺序分割成多组子列表。

对比函数只比较相邻元素。

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']

gt Relation

Ord a => a → a → Boolean
Parameters
  • a
  • b
Returns Boolean

Added in v0.1.0

如果首个参数大于第二个参数,返回 true;否则返回 false

See also lt.
R.gt(2, 1); //=> true R.gt(2, 2); //=> false R.gt(2, 3); //=> false R.gt('a', 'z'); //=> false R.gt('z', 'a'); //=> true

gte Relation

Ord a => a → a → Boolean
Parameters
  • a
  • b
Returns Boolean

Added in v0.1.0

如果首个参数大于或等于第二个参数,返回 true;否则返回 false

See also lte.
R.gte(2, 1); //=> true R.gte(2, 2); //=> true R.gte(2, 3); //=> false R.gte('a', 'z'); //=> false R.gte('z', 'a'); //=> true

has Object

s → {s: x} → Boolean
Parameters
  • prop

    The name of the property to check for.

  • obj

    The object to query.

Returns Boolean Whether the property exists.

Added in v0.7.0

如果对象自身含有指定的属性,则返回 true;否则返回 false

const hasName = R.has('name'); hasName({name: 'alice'}); //=> true hasName({name: 'bob'}); //=> true hasName({}); //=> false const point = {x: 0, y: 0}; const pointHas = R.has(R.__, point); pointHas('x'); //=> true pointHas('y'); //=> true pointHas('z'); //=> false

hasIn Object

s → {s: x} → Boolean
Parameters
  • prop

    The name of the property to check for.

  • obj

    The object to query.

Returns Boolean Whether the property exists.

Added in v0.7.0

如果对象自身或其原型链上含有指定的属性,则返回 true;否则返回 false

function Rectangle(width, height) { this.width = width; this.height = height; } Rectangle.prototype.area = function() { return this.width * this.height; }; const square = new Rectangle(2, 2); R.hasIn('width', square); //=> true R.hasIn('area', square); //=> true

hasPath Object

[Idx] → {a} → Boolean
Idx = String | Int | Symbol
Parameters
  • path

    The path to use.

  • obj

    The object to check the path in.

Returns Boolean Whether the path exists.

Added in v0.26.0

检查对象中是否存在指定的路径。只检查对象自身的属性。

See also has.
R.hasPath(['a', 'b'], {a: {b: 2}}); // => true R.hasPath(['a', 'b'], {a: {b: undefined}}); // => true R.hasPath(['a', 'b'], {a: {c: 2}}); // => false R.hasPath(['a', 'b'], {}); // => false

head List

[a] → a | Undefined
String → String
Parameters
  • list
Returns *

Added in v0.1.0

求列表或字符串的首个元素。在某些库中,该函数也被称作 first

See also tail, init, last.
R.head(['fi', 'fo', 'fum']); //=> 'fi' R.head([]); //=> undefined R.head('abc'); //=> 'a' R.head(''); //=> ''

identical Relation

a → a → Boolean
Parameters
  • a
  • b
Returns Boolean

Added in v0.15.0

如果两个参数是完全相同,则返回 true,否则返回 false。如果它们引用相同的内存,也认为是完全相同的。NaNNaN 是完全相同的;0-0 不是完全相同的。

注意:这只是 ES6 Object.is 的柯里化版本而已。

identical 不支持 __ 占位符。

const 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

a → a
Parameters
  • x

    The value to return.

Returns * The input value, `x`.

Added in v0.1.0

将输入值原样返回。适合用作默认或占位函数。

R.identity(1); //=> 1 const obj = {}; R.identity(obj) === obj; //=> true

ifElse Logic

(*… → Boolean) → (*… → *) → (*… → *) → (*… → *)
Parameters
  • condition

    A predicate function

  • onTrue

    A function to invoke when the condition evaluates to a truthy value.

  • onFalse

    A function to invoke when the condition evaluates to a falsy value.

Returns function A new function that will process either the `onTrue` or the `onFalse` function depending upon the result of the `condition` predicate.

Added in v0.8.0

根据 condition predicate 的返回值调用 onTrueonFalse 函数。

See also unless, when, cond.
const incCount = R.ifElse( R.has('count'), R.over(R.lensProp('count'), R.inc), R.assoc('count', 1) ); incCount({ count: 1 }); //=> { count: 2 } incCount({}); //=> { count: 1 }

inc Math

Number → Number
Parameters
  • n
Returns Number n + 1

Added in v0.9.0

加1。

See also dec.
R.inc(42); //=> 43

includes List

a → [a] → Boolean
Parameters
  • a

    The item to compare against.

  • list

    The array to consider.

Returns Boolean `true` if an equivalent item is in the list, `false` otherwise.

Added in v0.26.0

只要列表中有一个元素等于指定值,则返回 true;否则返回 false。通过 R.equals 函数进行相等性判断。

也可以判断字符串中是否包含指定值。

See also any.
R.includes(3, [1, 2, 3]); //=> true R.includes(4, [1, 2, 3]); //=> false R.includes({ name: 'Fred' }, [{ name: 'Fred' }]); //=> true R.includes([42], [[42]]); //=> true R.includes('ba', 'banana'); //=>true

indexBy List

Idx a => (b → a) → [b] → {a: b}
Idx = String | Int | Symbol
Parameters
  • fn

    Function :: a -> Idx

  • array

    The array of objects to index

Returns Object An object indexing each array element by the given property.

Added in v0.19.0

通过生成键的函数,将元素为对象的 list 转换为以生成的键为索引的新对象。注意,如果 list 中多个对象元素生成相同的键,以最后一个对象元素作为该键的值。

若在 list 位置中给出 transfomer ,则用作 transducer

See also groupBy.
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'}}

indexOf List

a → [a] → Number
Parameters
  • target

    The item to find.

  • xs

    The array to search in.

Returns Number the index of the target, or -1 if the target is not found.

Added in v0.1.0

返回给定元素在数组中首次出现时的索引值,如果数组中没有该元素,则返回 -1。通过 R.equals 函数进行相等性判断。

See also lastIndexOf, findIndex.
R.indexOf(3, [1,2,3,4]); //=> 2 R.indexOf(10, [1,2,3,4]); //=> -1

init List

[a] → [a]
String → String
Parameters
  • list
Returns *

Added in v0.9.0

返回 list 或 string 删除最后一个元素后的部分。

See also last, head, tail.
R.init([1, 2, 3]); //=> [1, 2] R.init([1, 2]); //=> [1] R.init([1]); //=> [] R.init([]); //=> [] R.init('abc'); //=> 'ab' R.init('ab'); //=> 'a' R.init('a'); //=> '' R.init(''); //=> ''

innerJoin Relation

((a, b) → Boolean) → [a] → [b] → [a]
Parameters
  • pred
  • xs
  • ys
Returns Array

Added in v0.24.0

接受一个 predicate pred 、列表 xsys ,返回列表 xs'。依次取出 xs 中的元素,若通过 pred 判断等于 ys 中的一个或多个元素,则放入 xs'

pred 必须为二元函数,两个参数分别来自于对应两个列表中的元素。

xsysxs' 被当作集合处理,所以从语义上讲,元素的顺序并不重要,但由于 xs' 是列表(列表中元素有排列顺序),所以本实现保证 xs' 中元素的顺序与 xs 中的一致。重复的元素也不会被移除,因此,若 xs 中含重复元素,xs' 中也会包含元素。

See also intersection.
R.innerJoin( (record, id) => record.id === id, [{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'}], [177, 456, 999] ); //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}]

insert List

Number → a → [a] → [a]
Parameters
  • index

    The position to insert the element

  • elt

    The element to insert into the Array

  • list

    The list to insert into

Returns Array A new Array with `elt` inserted at `index`.

Added in v0.2.2

将元素插入到 list 指定索引处。注意,该函数是非破坏性的:返回处理后列表的拷贝。函数运行过程中不会破坏任何列表。

R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4]

insertAll List

Number → [a] → [a] → [a]
Parameters
  • index

    The position to insert the sub-list

  • elts

    The sub-list to insert into the Array

  • list

    The list to insert the sub-list into

Returns Array A new Array with `elts` inserted starting at `index`.

Added in v0.9.0

将子 list 插入到 list 指定索引处。注意,该函数是非破坏性的:返回处理后列表的拷贝。函数运行过程中不会破坏任何列表。

R.insertAll(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4]

intersection Relation

[*] → [*] → [*]
Parameters
  • list1

    The first list.

  • list2

    The second list.

Returns Array The list of elements found in both `list1` and `list2`.

Added in v0.1.0

取出两个 list 中相同的元素组成的 set (集合:没有重复元素)。

See also innerJoin.
R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3]

intersperse List

a → [a] → [a]
Parameters
  • separator

    The element to add to the list.

  • list

    The list to be interposed.

Returns Array The new list.

Added in v0.14.0

在列表的元素之间插入分割元素。

若第二个参数自身存在 intersperse 方法,则调用自身的 intersperse 方法。

R.intersperse('a', ['b', 'n', 'n', 's']); //=> ['b', 'a', 'n', 'a', 'n', 'a', 's']

into List

a → (b → b) → [c] → a
Parameters
  • acc

    The initial accumulator value.

  • xf

    The transducer function. Receives a transformer and returns a transformer.

  • list

    The list to iterate over.

Returns * The final, accumulated value.

Added in v0.12.0

使用 transducer 对 list 中的元素进行转换,然后使用基于 accumulator 的类型的迭代器函数将转换后的元素依次添加到 accumulator 上。

accumulator 的类型可以是:array、string、object 或者 transformer 。如果 accumulator 类型是 array 或 string,则迭代元素将被添加到数组或连接到字符串上;如果是对象,迭代元素将会被直接合并;如果是二元素数组,迭代元素会以键值对形式进行合并。

accumulator 也可作为 transformer 对象,提供 transformer 所需要的二元 reducing iterator、step、零元 init 和 一元 result 函数。step 作为 reduce 过程中的迭代函数;result 将最终的 accumulator 转换为需要的返回类型(通常为 R.identity);init 提供初始 accumulator。

在 transducer 初始化之后,使用 R.reduce 进行迭代操作。

See also transduce.
const numbers = [1, 2, 3, 4]; const transducer = R.compose(R.map(R.add(1)), R.take(2)); R.into([], transducer, numbers); //=> [2, 3] const intoArray = R.into([]); intoArray(transducer, numbers); //=> [2, 3]

invert Object

{s: x} → {x: [ s, … ]}
Parameters
  • obj

    The object or array to invert

Returns Object out A new object with keys in an array.

Added in v0.9.0

R.invertObj 类似,但会将值放入数组中,来处理一个键对应多个值的情况。

See also invertObj.
const raceResultsByFirstName = { first: 'alice', second: 'jake', third: 'alice', }; R.invert(raceResultsByFirstName); //=> { 'alice': ['first', 'third'], 'jake':['second'] }

invertObj Object

{s: x} → {x: s}
Parameters
  • obj

    The object or array to invert

Returns Object out A new object

Added in v0.9.0

将对象的键、值交换位置:值作为键,对应的键作为值。交换后的键会被强制转换为字符串。注意,如果原对象同一值对应多个键,采用最后遍历到的键。

See also invert.
const raceResults = { first: 'alice', second: 'jake' }; R.invertObj(raceResults); //=> { 'alice': 'first', 'jake':'second' } // Alternatively: const raceResults = ['alice', 'jake']; R.invertObj(raceResults); //=> { 'alice': '0', 'jake':'1' }

invoker Function

Number → String → (a → b → … → n → Object → *)
Parameters
  • arity

    Number of arguments the returned function should take before the target object.

  • method

    Name of any of the target object's methods to call.

Returns function A new curried function.

Added in v0.1.0

将具有指定元数(参数个数)的具名方法,转换为可以被给定参数和目标对象直接调用的函数。

返回的函数是柯里化的,它接收 arity + 1 个参数,其中最后一个参数是目标对象。

See also construct.
const sliceFrom = R.invoker(1, 'slice'); sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm' const sliceFrom6 = R.invoker(2, 'slice')(6); sliceFrom6(8, 'abcdefghijklm'); //=> 'gh' const dog = { speak: async () => 'Woof!' }; const speak = R.invoker(0, 'speak'); speak(dog).then(console.log) //~> 'Woof!'

is Type

(* → {*}) → a → Boolean
Parameters
  • ctor

    A constructor

  • val

    The value to test

Returns Boolean

Added in v0.3.0

检测一个对象(val)是否是给定构造函数的实例。该函数会依次检测其原型链,如果存在的话。

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

isEmpty Logic

a → Boolean
Parameters
  • x
Returns Boolean

Added in v0.1.0

检测给定值是否为其所属类型的空值,若是则返回 true ;否则返回 false

See also empty.
R.isEmpty([1, 2, 3]); //=> false R.isEmpty([]); //=> true R.isEmpty(''); //=> true R.isEmpty(null); //=> false R.isEmpty({}); //=> true R.isEmpty({length: 0}); //=> false R.isEmpty(Uint8Array.from('')); //=> true

isNil Type

* → Boolean
Parameters
  • x

    The value to test.

Returns Boolean `true` if `x` is `undefined` or `null`, otherwise `false`.

Added in v0.9.0

检测输入值是否为 nullundefined

R.isNil(null); //=> true R.isNil(undefined); //=> true R.isNil(0); //=> false R.isNil([]); //=> false

join List

String → [a] → String
Parameters
  • separator

    The string used to separate the elements.

  • xs

    The elements to join into a string.

Returns String str The string made by concatenating `xs` with `separator`.

Added in v0.1.0

将列表中所有元素通过 分隔符 串连为一个字符串。

See also split.
const spacer = R.join(' '); spacer(['a', 2, 3.4]); //=> 'a 2 3.4' R.join('|', [1, 2, 3]); //=> '1|2|3'

juxt Function

[(a, b, …, m) → n] → ((a, b, …, m) → [n])
Parameters
  • fns

    An array of functions

Returns function A function that returns a list of values after applying each of the original `fns` to its parameters.

Added in v0.19.0

juxt 将函数列表作用于值列表。

See also applySpec.
const getRange = R.juxt([Math.min, Math.max]); getRange(3, 4, 9, -3); //=> [-3, 9]

keys Object

{k: v} → [k]
Parameters
  • obj

    The object to extract properties from

Returns Array An array of the object's own properties.

Added in v0.1.0

返回给定对象所有可枚举的、自身属性的属性名组成的列表。注意,不同 JS 运行环境输出数组的顺序可能不一致。

See also keysIn, values, toPairs.
R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']

keysIn Object

{k: v} → [k]
Parameters
  • obj

    The object to extract properties from

Returns Array An array of the object's own and prototype properties.

Added in v0.2.0

返回给定对象所有属性(包括 prototype 属性)的属性名组成的列表。注意,不同 JS 运行环境输出数组的顺序可能不一致。

See also keys, valuesIn.
const F = function() { this.x = 'X'; }; F.prototype.y = 'Y'; const f = new F(); R.keysIn(f); //=> ['x', 'y']

last List

[a] → a | Undefined
String → String
Parameters
  • list
Returns *

Added in v0.1.4

返回列表或字符串的最后一个元素。

See also init, head, tail.
R.last(['fi', 'fo', 'fum']); //=> 'fum' R.last([]); //=> undefined R.last('abc'); //=> 'c' R.last(''); //=> ''

lastIndexOf List

a → [a] → Number
Parameters
  • target

    The item to find.

  • xs

    The array to search in.

Returns Number the index of the target, or -1 if the target is not found.

Added in v0.1.0

返回数组中某元素最后一次出现的位置,如果数组中不包含该项则返回 -1 。通过 R.equals 函数进行相等性判断。

See also indexOf, findLastIndex.
R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6 R.lastIndexOf(10, [1,2,3,4]); //=> -1

length List

[a] → Number
Parameters
  • list

    The array to inspect.

Returns Number The length of the array.

Added in v0.3.0

通过 list.length,返回数组的大小(数组中元素的数量)。

R.length([]); //=> 0 R.length([1, 2, 3]); //=> 3

lens Object

(s → a) → ((a, s) → s) → Lens s a
Lens s a = Functor f => (a → f a) → s → f s
Parameters
  • getter
  • setter
Returns Lens

Added in v0.8.0

返回封装了给定 getter 和 setter 方法的 lens 。 getter 和 setter 分别用于 “获取” 和 “设置” 焦点(lens 聚焦的值)。setter 不会改变原数据。

See also view, set, over, lensIndex, lensProp.
const xLens = R.lens(R.prop('x'), R.assoc('x')); R.view(xLens, {x: 1, y: 2}); //=> 1 R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2}

lensIndex Object

Number → Lens s a
Lens s a = Functor f => (a → f a) → s → f s
Parameters
  • n
Returns Lens

Added in v0.14.0

返回聚焦到指定索引的 lens。

See also view, set, over, nth.
const headLens = R.lensIndex(0); R.view(headLens, ['a', 'b', 'c']); //=> 'a' R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c']

lensPath Object

[Idx] → Lens s a
Idx = String | Int | Symbol
Lens s a = Functor f => (a → f a) → s → f s
Parameters
  • path

    The path to use.

Returns Lens

Added in v0.19.0

返回聚焦到指定路径的 lens。

See also view, set, over.
const xHeadYLens = R.lensPath(['x', 0, 'y']); R.view(xHeadYLens, {x: [{y: 2, z: 3}, {y: 4, z: 5}]}); //=> 2 R.set(xHeadYLens, 1, {x: [{y: 2, z: 3}, {y: 4, z: 5}]}); //=> {x: [{y: 1, z: 3}, {y: 4, z: 5}]} R.over(xHeadYLens, R.negate, {x: [{y: 2, z: 3}, {y: 4, z: 5}]}); //=> {x: [{y: -2, z: 3}, {y: 4, z: 5}]}

lensProp Object

String → Lens s a
Lens s a = Functor f => (a → f a) → s → f s
Parameters
  • k
Returns Lens

Added in v0.14.0

返回聚焦到指定属性的 lens。

See also view, set, over.
const xLens = R.lensProp('x'); R.view(xLens, {x: 1, y: 2}); //=> 1 R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2}

lift Function

(*… → *) → ([*]… → [*])
Parameters
  • fn

    The function to lift into higher context

Returns function The lifted function.

Added in v0.7.0

提升一个多元函数,使之能映射到列表、函数或其他符合 FantasyLand Apply spec 规范的对象上。

See also liftN.
const madd3 = R.lift((a, b, c) => a + b + c); madd3([100, 200], [30, 40], [5, 6, 7]); //=> [135, 136, 137, 145, 146, 147, 235, 236, 237, 245, 246, 247] const madd5 = R.lift((a, b, c, d, e) => a + b + c + d + e); madd5([10, 20], [1], [2, 3], [4], [100, 200]); //=> [117, 217, 118, 218, 127, 227, 128, 228]

liftN Function

Number → (*… → *) → ([*]… → [*])
Parameters
  • fn

    The function to lift into higher context

Returns function The lifted function.

Added in v0.7.0

将一个函数提升为指定元数的函数,使之能映射到多个列表、函数或其他符合 FantasyLand Apply spec 规范的对象上。

See also lift, ap.
const madd3 = R.liftN(3, (...args) => R.sum(args)); madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]

lt Relation

Ord a => a → a → Boolean
Parameters
  • a
  • b
Returns Boolean

Added in v0.1.0

如果首个参数小于第二个参数,返回 true;否则返回 false

See also gt.
R.lt(2, 1); //=> false R.lt(2, 2); //=> false R.lt(2, 3); //=> true R.lt('a', 'z'); //=> true R.lt('z', 'a'); //=> false

lte Relation

Ord a => a → a → Boolean
Parameters
  • a
  • b
Returns Boolean

Added in v0.1.0

如果首个参数小于或等于第二个参数,返回 true;否则返回 false

See also gte.
R.lte(2, 1); //=> false R.lte(2, 2); //=> true R.lte(2, 3); //=> true R.lte('a', 'z'); //=> true R.lte('z', 'a'); //=> false

map List

Functor f => (a → b) → f a → f b
Parameters
  • fn

    The function to be called on every element of the input list.

  • list

    The list to be iterated over.

Returns Array The new list.

Added in v0.1.0

接收一个函数和一个 functor, 将该函数应用到 functor 的每个值上,返回一个具有相同形态的 functor。

Ramda 为 ArrayObject 提供了合适的 map 实现,因此 R.map 适用于 [1, 2, 3]{x: 1, y: 2, z: 3}

若第二个参数自身存在 map 方法,则调用自身的 map 方法。

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装 。

函数也是 functors,map 会将它们组合起来(相当于 R.compose)。

const double = x => x * 2; R.map(double, [1, 2, 3]); //=> [2, 4, 6] R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6}

mapAccum List

((acc, x) → (acc, y)) → acc → [x] → (acc, [y])
Parameters
  • fn

    The function to be called on every element of the input list.

  • acc

    The accumulator value.

  • list

    The list to iterate over.

Returns * The final, accumulated value.

Added in v0.10.0

mapAccum 的行为类似于 map 和 reduce 的组合;它将迭代函数作用于列表中的每个元素,从左往右传递经迭代函数计算的累积值,并将最后的累积值和由所有中间的累积值组成的列表一起返回。 迭代函数接收两个参数,accvalue, 返回一个元组 *[acc, value]*。

const digits = ['1', '2', '3', '4']; const appender = (a, b) => [a + b, a + b]; R.mapAccum(appender, 0, digits); //=> ['01234', ['01', '012', '0123', '01234']]

mapAccumRight List

((acc, x) → (acc, y)) → acc → [x] → (acc, [y])
Parameters
  • fn

    The function to be called on every element of the input list.

  • acc

    The accumulator value.

  • list

    The list to iterate over.

Returns * The final, accumulated value.

Added in v0.10.0

mapAccumRight 的行为类似于 map 和 reduce 的组合;它将迭代函数作用于列表中的每个元素,从右往左传递经迭代函数计算的累积值,并将最后的累积值和由所有中间的累积值组成的列表一起返回。

mapAccum 类似,除了列表遍历顺序是从右往左的。

迭代函数接收两个参数,accvalue ,返回一个元组 *[acc, value]*。

See also addIndex, mapAccum.
const digits = ['1', '2', '3', '4']; const appender = (a, b) => [b + a, b + a]; R.mapAccumRight(appender, 5, digits); //=> ['12345', ['12345', '2345', '345', '45']]

mapObjIndexed Object

((*, String, Object) → *) → Object → Object
Parameters
  • fn
  • obj
Returns Object

Added in v0.9.0

Object 版本的 map。mapping function 接受三个参数: (value, key, obj) 。如果仅用到参数 value,则用 map 即可。

See also map.
const xyz = { x: 1, y: 2, z: 3 }; const prependKeyAndDouble = (num, key, obj) => key + (num * 2); R.mapObjIndexed(prependKeyAndDouble, xyz); //=> { x: 'x2', y: 'y4', z: 'z6' }

match String

RegExp → String → [String | Undefined]
Parameters
  • rx

    A regular expression.

  • str

    The string to match against

Returns Array The list of matches or empty array.

Added in v0.1.0

正则匹配字符串。注意,如果没有匹配项,则返回空数组。和 String.prototype.match 不同,后者在没有匹配项时会返回 null

See also test.
R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na'] R.match(/a/, 'b'); //=> [] R.match(/a/, null); //=> TypeError: null does not have a method named "match"

mathMod Math

Number → Number → Number
Parameters
  • m

    The dividend.

  • p

    the modulus.

Returns Number The result of `b mod a`.

Added in v0.3.0

mathMod 和算术取模操作类似,而不像 % 操作符 (或 R.modulo)。所以 -17 % 5 等于 -2,而 mathMod(-17, 5) 等于 3mathMod 要求参数为整型,并且当模数等于 0 或者负数时返回 NaN 。

See also modulo.
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 const clock = R.mathMod(R.__, 12); clock(15); //=> 3 clock(24); //=> 0 const seventeenMod = R.mathMod(17); seventeenMod(3); //=> 2 seventeenMod(4); //=> 1 seventeenMod(10); //=> 7

max Relation

Ord a => a → a → a
Parameters
  • a
  • b
Returns *

Added in v0.1.0

返回两个参数中的较大值。

See also maxBy, min.
R.max(789, 123); //=> 789 R.max('a', 'b'); //=> 'b'

maxBy Relation

Ord b => (a → b) → a → a → a
Parameters
  • f
  • a
  • b
Returns *

Added in v0.8.0

接收一个函数和两个值,返回使给定函数执行结果较大的值。

See also max, minBy.
// square :: Number -> Number const square = n => n * n; R.maxBy(square, -3, 2); //=> -3 R.reduce(R.maxBy(square), 0, [3, -5, 4, 1, -2]); //=> -5 R.reduce(R.maxBy(square), 0, []); //=> 0

mean Math

[Number] → Number
Parameters
  • list
Returns Number

Added in v0.14.0

返回给定数字列表的平均值。

See also median.
R.mean([2, 7, 9]); //=> 6 R.mean([]); //=> NaN

median Math

[Number] → Number
Parameters
  • list
Returns Number

Added in v0.14.0

返回给定数字列表的中位数。

See also mean.
R.median([2, 9, 7]); //=> 7 R.median([7, 2, 10, 9]); //=> 8 R.median([]); //=> NaN

memoizeWith Function

(*… → String) → (*… → a) → (*… → a)
Parameters
  • fn

    The function to generate the cache key.

  • fn

    The function to memoize.

Returns function Memoized version of `fn`.

Added in v0.24.0

创建一个新函数,当调用时,会执行原函数,输出结果;并且缓存本次的输入参数及其对应的结果。 后续,若用相同的参数对缓存函数进行调用,不会再执行原函数,而是直接返回该参数对应的缓存值。

memoizeWith 接受两个函数,第一个会将输入参数序列化为缓存键值对的“键值”,第二个是需要缓存的函数。

let count = 0; const factorial = R.memoizeWith(Number, n => { count += 1; return R.product(R.range(1, n + 1)); }); factorial(5); //=> 120 factorial(5); //=> 120 factorial(5); //=> 120 count; //=> 1

mergeAll List

[{k: v}] → {k: v}
Parameters
  • list

    An array of objects

Returns Object A merged object.

Added in v0.10.0

将对象类型列表合并为一个对象。

See also reduce.
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}

mergeDeepLeft Object

{a} → {a} → {a}
Parameters
  • lObj
  • rObj
Returns Object

Added in v0.24.0

合并两个对象的自身属性(不包括 prototype 属性)。如果某个 key 在两个对象中都存在:

  • 并且两个值都是对象,则继续递归合并这两个值。
  • 否则,采用第一个对象的值。
R.mergeDeepLeft({ name: 'fred', age: 10, contact: { email: 'moo@example.com' }}, { age: 40, contact: { email: 'baa@example.com' }}); //=> { name: 'fred', age: 10, contact: { email: 'moo@example.com' }}

mergeDeepRight Object

{a} → {a} → {a}
Parameters
  • lObj
  • rObj
Returns Object

Added in v0.24.0

合并两个对象的自身属性(不包括 prototype 属性)。如果某个 key 在两个对象中都存在:

  • 并且两个值都是对象,则继续递归合并这两个值。
  • 否则,采用第二个对象的值。
R.mergeDeepRight({ name: 'fred', age: 10, contact: { email: 'moo@example.com' }}, { age: 40, contact: { email: 'baa@example.com' }}); //=> { name: 'fred', age: 40, contact: { email: 'baa@example.com' }}

mergeDeepWith Object

((a, a) → a) → {a} → {a} → {a}
Parameters
  • fn
  • lObj
  • rObj
Returns Object

Added in v0.24.0

合并两个对象的自身属性(不包括 prototype 属性)。如果某个 key 在两个对象中都存在:

  • 并且两个关联的值都是对象,则继续递归合并这两个值。
  • 否则,使用给定函数对两个值进行处理,并将返回值作为该 key 的新值。

如果某 key 只存在于一个对象中,该键值对将作为结果对象的键值对。

R.mergeDeepWith(R.concat, { a: true, c: { values: [10, 20] }}, { b: true, c: { values: [15, 35] }}); //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }}

mergeDeepWithKey Object

((String, a, a) → a) → {a} → {a} → {a}
Parameters
  • fn
  • lObj
  • rObj
Returns Object

Added in v0.24.0

合并两个对象的自身属性(不包括 prototype 属性)。如果某个 key 在两个对象中都存在:

  • 并且两个关联的值都是对象,则继续递归合并这两个值。
  • 否则,使用给定函数对该 key 和对应的两个值进行处理,并将返回值作为该 key 的新值。

如果某 key 只存在于一个对象中,该键值对将作为结果对象的键值对。

let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r R.mergeDeepWithKey(concatValues, { a: true, c: { thing: 'foo', values: [10, 20] }}, { b: true, c: { thing: 'bar', values: [15, 35] }}); //=> { a: true, b: true, c: { thing: 'bar', values: [10, 20, 15, 35] }}

mergeLeft Object

{k: v} → {k: v} → {k: v}
Parameters
  • l
  • r
Returns Object

Added in v0.26.0

合并两个对象的自身属性(不包括 prototype 属性)。如果某个 key 在两个对象中都存在,使用前一个对象对应的属性值。

R.mergeLeft({ 'age': 40 }, { 'name': 'fred', 'age': 10 }); //=> { 'name': 'fred', 'age': 40 } const resetToDefault = R.mergeLeft({x: 0}); resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2}

mergeRight Object

{k: v} → {k: v} → {k: v}
Parameters
  • l
  • r
Returns Object

Added in v0.26.0

合并两个对象的自身属性(不包括 prototype 属性)。如果某个 key 在两个对象中都存在,使用后一个对象对应的属性值。

R.mergeRight({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); //=> { 'name': 'fred', 'age': 40 } const withDefaults = R.mergeRight({x: 0, y: 0}); withDefaults({y: 2}); //=> {x: 0, y: 2}

mergeWith Object

((a, a) → a) → {a} → {a} → {a}
Parameters
  • fn
  • l
  • r
Returns Object

Added in v0.19.0

使用给定的两个对象自身属性(不包括 prototype 属性)来创建一个新对象。

如果某个 key 在两个对象中都存在,则使用给定的函数对每个对象该 key 对应的 value 进行处理,处理结果作为新对象该 key 对应的值。

R.mergeWith(R.concat, { a: true, values: [10, 20] }, { b: true, values: [15, 35] }); //=> { a: true, b: true, values: [10, 20, 15, 35] }

mergeWithKey Object

((String, a, a) → a) → {a} → {a} → {a}
Parameters
  • fn
  • l
  • r
Returns Object

Added in v0.19.0

使用给定的两个对象自身属性(不包括 prototype 属性)来创建一个新对象。

如果某个 key 在两个对象中都存在,则使用给定的函数对该 key 和每个对象该 key 对应的 value 进行处理,处理结果作为新对象该 key 对应的值。

let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r R.mergeWithKey(concatValues, { a: true, thing: 'foo', values: [10, 20] }, { b: true, thing: 'bar', values: [15, 35] }); //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] }

min Relation

Ord a => a → a → a
Parameters
  • a
  • b
Returns *

Added in v0.1.0

返回两个参数中的较小值。

See also minBy, max.
R.min(789, 123); //=> 123 R.min('a', 'b'); //=> 'a'

minBy Relation

Ord b => (a → b) → a → a → a
Parameters
  • f
  • a
  • b
Returns *

Added in v0.8.0

接收一个函数和两个值,返回使给定函数执行结果较小的值。

See also min, maxBy.
// square :: Number -> Number const square = n => n * n; R.minBy(square, -3, 2); //=> 2 R.reduce(R.minBy(square), Infinity, [3, -5, 4, 1, -2]); //=> 1 R.reduce(R.minBy(square), Infinity, []); //=> Infinity

modify Object

Idx → (v → v) → {k: v} → {k: v}
Parameters
  • prop

    The property to be modified.

  • fn

    The function to apply to the property.

  • object

    The object to be transformed.

Returns Object The transformed object.

Added in v0.28.0

使用给定的函数,修改对象中指定属性的值。

如果对象上没有对应的属性,那么这个函数不会被调用,且对象不会被改变。 所有的非基础类型是通过引用拷贝到新的对象上。

const person = {name: 'James', age: 20, pets: ['dog', 'cat']}; R.modify('age', R.add(1), person); //=> {name: 'James', age: 21, pets: ['dog', 'cat']} R.modify('pets', R.append('turtle'), person); //=> {name: 'James', age: 20, pets: ['dog', 'cat', 'turtle']}

modifyPath Object

[Idx] → (v → v) → {k: v} → {k: v}
Parameters
  • path

    The path to be modified.

  • fn

    The function to apply to the path.

  • object

    The object to be transformed.

Returns Object The transformed object.

Added in v0.28.0

使用给定的函数,修改对象中指定路径的值。

如果对象上没有对应的属性,那么这个函数不会被调用,且对象不会被改变。 所有的非基础类型是通过引用拷贝到新的对象上。

const person = {name: 'James', address: { zipCode: '90216' }}; R.modifyPath(['address', 'zipCode'], R.reverse, person); //=> {name: 'James', address: { zipCode: '61209' }} // Can handle arrays too const person = {name: 'James', addresses: [{ zipCode: '90216' }]}; R.modifyPath(['addresses', 0, 'zipCode'], R.reverse, person); //=> {name: 'James', addresses: [{ zipCode: '61209' }]}

modulo Math

Number → Number → Number
Parameters
  • a

    The value to the divide.

  • b

    The pseudo-modulus

Returns Number The result of `b % a`.

Added in v0.1.1

用第一个参数除以第二个参数,并返回余数。注意,该函数是 JavaScript-style 的求模操作。数学求模另见 mathMod

See also mathMod.
R.modulo(17, 3); //=> 2 // JS behavior: R.modulo(-17, 3); //=> -2 R.modulo(17, -3); //=> 2 const isOdd = R.modulo(R.__, 2); isOdd(42); //=> 0 isOdd(21); //=> 1

move List

Number → Number → [a] → [a]
Parameters
  • from

    The source index

  • to

    The destination index

  • list

    The list which will serve to realise the move

Returns Array The new list reordered

Added in v0.27.1

将列表中 from 索引处的元素移动到索引 to 处。

R.move(0, 2, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['b', 'c', 'a', 'd', 'e', 'f'] R.move(-1, 0, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['f', 'a', 'b', 'c', 'd', 'e'] list rotation

multiply Math

Number → Number → Number
Parameters
  • a

    The first value.

  • b

    The second value.

Returns Number The result of `a * b`.

Added in v0.1.0

两数相乘,等价于柯里化的 a * b

See also divide.
const double = R.multiply(2); const triple = R.multiply(3); double(3); //=> 6 triple(4); //=> 12 R.multiply(2, 5); //=> 10

nAry Function

Number → (* → a) → (* → a)
Parameters
  • n

    The desired arity of the new function.

  • fn

    The function to wrap.

Returns function A new function wrapping `fn`. The new function is guaranteed to be of arity `n`.

Added in v0.1.0

将一个任意元(包括零元)的函数,封装成一个确定元数(参数个数)的函数。任何多余的参数都不会传入被封装的函数。

See also binary, unary.
const takesTwoArgs = (a, b) => [a, b]; takesTwoArgs.length; //=> 2 takesTwoArgs(1, 2); //=> [1, 2] const 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 → Number
Parameters
  • n
Returns Number

Added in v0.9.0

取反操作。

R.negate(42); //=> -42

none List

(a → Boolean) → [a] → Boolean
Parameters
  • fn

    The predicate function.

  • list

    The array to consider.

Returns Boolean `true` if the predicate is not satisfied by every element, `false` otherwise.

Added in v0.12.0

如果列表中的元素都不满足 predicate,返回 true;否则返回 false

若第二个参数自身存在 none 方法,则调用自身的 none 方法。

See also all, any.
const isEven = n => n % 2 === 0; const isOdd = n => n % 2 !== 0; R.none(isEven, [1, 3, 5, 7, 9, 11]); //=> true R.none(isOdd, [1, 3, 5, 7, 8, 11]); //=> false

not Logic

* → Boolean
Parameters
  • a

    any value

Returns Boolean the logical inverse of passed argument.

Added in v0.1.0

逻辑非运算。 当传入参数为 false-y 值时,返回 true;truth-y 值时,返回 false

See also complement.
R.not(true); //=> false R.not(false); //=> true R.not(0); //=> true R.not(1); //=> false

nth List

Number → [a] → a | Undefined
Number → String → String
Parameters
  • offset
  • list
Returns *

Added in v0.1.0

返回列表或字符串的第 n 个元素。如果 n 为负数,则返回索引为 length + n 的元素。

const list = ['foo', 'bar', 'baz', 'quux']; R.nth(1, list); //=> 'bar' R.nth(-1, list); //=> 'quux' R.nth(-99, list); //=> undefined R.nth(2, 'abc'); //=> 'c' R.nth(3, 'abc'); //=> ''

nthArg Function

Number → *… → *
Parameters
  • n
Returns function

Added in v0.9.0

返回一个函数,该函数返回它的第 n 个参数。

R.nthArg(1)('a', 'b', 'c'); //=> 'b' R.nthArg(-1)('a', 'b', 'c'); //=> 'c'

o Function

(b → c) → (a → b) → a → c
Parameters
  • f
  • g
Returns function

Added in v0.24.0

o 是一个柯里化组合函数,返回一元函数。

类似于 composeo 从右到左执行函数组合。但与 compose 不同的是,传递给 o 的最右边的函数为一元函数。

See also compose, pipe.
const classyGreeting = name => "The name's " + name.last + ", " + name.first + " " + name.last const yellGreeting = R.o(R.toUpper, classyGreeting); yellGreeting({first: 'James', last: 'Bond'}); //=> "THE NAME'S BOND, JAMES BOND" R.o(R.multiply(10), R.add(10))(-4) //=> 60

objOf Object

String → a → {String:a}
Parameters
  • key
  • val
Returns Object

Added in v0.18.0

创建一个包含单个键值对的对象。

See also pair.
const matchPhrases = R.compose( R.objOf('must'), R.map(R.objOf('match_phrase')) ); matchPhrases(['foo', 'bar', 'baz']); //=> {must: [{match_phrase: 'foo'}, {match_phrase: 'bar'}, {match_phrase: 'baz'}]}

of Function

a → [a]
Parameters
  • x

    any value

Returns Array An array wrapping `x`.

Added in v0.3.0

将给定值作为元素,封装成单元素数组。

注意,R.of 与 ES6 的 of 不同;详见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of

R.of(null); //=> [null] R.of([42]); //=> [[42]]

omit Object

[String] → {String: *} → {String: *}
Parameters
  • names

    an array of String property names to omit from the new object

  • obj

    The object to copy from

Returns Object A new object with properties from `names` not on it.

Added in v0.1.0

删除对象中给定的 keys 对应的属性。

See also pick.
R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}

on Function

((a, a) → b) → (c → a) → c → c → b
Parameters
  • f

    a binary function

  • g

    a unary function

  • a

    any value

  • b

    any value

Returns any The result of `f`

Added in v0.28.0

接收一个二元函数 f,一个一元函数 g 和两个值。将两个值应用到函数 g 上,在把返回的结果应用到函数 f 上。

也被称为 P combinator。

const eqBy = R.on((a, b) => a === b); eqBy(R.prop('a'), {b:0, a:1}, {a:1}) //=> true; const containsInsensitive = R.on(R.contains, R.toLower); containsInsensitive('o', 'FOO'); //=> true

once Function

(a… → b) → (a… → b)
Parameters
  • fn

    The function to wrap in a call-only-once wrapper.

Returns function The wrapped function.

Added in v0.1.0

创建一个只执行一次的函数。

将给定函数 fn 封装到新函数fn'中,fn' 确保 fn 只能调用一次。重复调用fn' ,只会返回第一次执行时的结果。

const addOneOnce = R.once(x => x + 1); addOneOnce(10); //=> 11 addOneOnce(addOneOnce(50)); //=> 11

or Logic

a → b → a | b
Parameters
  • a
  • b
Returns Any

Added in v0.1.0

逻辑或运算,

只要有一个参数为真(truth-y),就返回 true;否则返回 false

See also either, and.
R.or(true, true); //=> true R.or(true, false); //=> true R.or(false, true); //=> true R.or(false, false); //=> false

otherwise Function

(e → b) → (Promise e a) → (Promise e b)
(e → (Promise f b)) → (Promise e a) → (Promise f b)
Parameters
  • onFailure

    The function to apply. Can return a value or a promise of a value.

  • p
Returns Promise The result of calling `p.then(null, onFailure)`

Added in v0.26.0

将 onFailure 函数应用于一个失败 Promise 的内部值,并将计算结果放入新的 Promise 中返回。这对于处理函数组合内的 rejected promises 很有用。

相当于 Promisecatch

See also andThen.
const failedFetch = id => Promise.reject('bad ID'); const useDefault = () => ({ firstName: 'Bob', lastName: 'Loblaw' }); //recoverFromFailure :: String -> Promise ({ firstName, lastName }) const recoverFromFailure = R.pipe( failedFetch, R.otherwise(useDefault), R.andThen(R.pick(['firstName', 'lastName'])), ); recoverFromFailure(12345).then(console.log);

over Object

Lens s a → (a → a) → s → s
Lens s a = Functor f => (a → f a) → s → f s
Parameters
  • lens
  • v
  • x
Returns *

Added in v0.16.0

对数据结构中被 lens 聚焦的部分进行函数变换。

const headLens = R.lensIndex(0); R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz']

pair List

a → b → (a,b)
Parameters
  • fst
  • snd
Returns Array

Added in v0.18.0

接收两个参数,fstsnd,返回数组 [fst, snd]

See also objOf, of.
R.pair('foo', 'bar'); //=> ['foo', 'bar']

partial Function

((a, b, c, …, n) → x) → [a, b, c, …] → ((d, e, f, …, n) → x)
Parameters
  • f
  • args
Returns function

Added in v0.10.0

部分应用。

接收两个参数:函数 f 和 参数列表,返回函数 g。当调用 g 时,将初始参数和 g 的参数顺次传给 f,并返回 f 的执行结果。

See also partialRight, curry.
const multiply2 = (a, b) => a * b; const double = R.partial(multiply2, [2]); double(3); //=> 6 const greet = (salutation, title, firstName, lastName) => salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; const sayHello = R.partial(greet, ['Hello']); const sayHelloToMs = R.partial(sayHello, ['Ms.']); sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!'

partialObject Function

(({ a, b, c, …, n }) → x) → { a, b, c, …} → ({ d, e, f, …, n } → x)
Parameters
  • f
  • props
Returns function

Added in v0.28.0

接受两个参数:函数 f 和对象 o1,返回一个函数 g。当 g 调用,将 g 的参数对象 o2o1 深度合并后传给 f,并返回 f 的执行结果。

const multiply2 = ({ a, b }) => a * b; const double = R.partialObject(multiply2, { a: 2 }); double({ b: 2 }); //=> 4 const greet = ({ salutation, title, firstName, lastName }) => salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; const sayHello = R.partialObject(greet, { salutation: 'Hello' }); const sayHelloToMs = R.partialObject(sayHello, { title: 'Ms.' }); sayHelloToMs({ firstName: 'Jane', lastName: 'Jones' }); //=> 'Hello, Ms. Jane Jones!'

partialRight Function

((a, b, c, …, n) → x) → [d, e, f, …, n] → ((a, b, c, …) → x)
Parameters
  • f
  • args
Returns function

Added in v0.10.0

部分应用。

接收两个参数:函数 f 和 参数列表,返回函数 g。当调用 g 时,将 g 的参数和初始参数顺序传给 f,并返回 f 的执行结果。

See also partial.
const greet = (salutation, title, firstName, lastName) => salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; const greetMsJaneJones = R.partialRight(greet, ['Ms.', 'Jane', 'Jones']); greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!'

partition List

Filterable f => (a → Boolean) → f a → [f a, f a]
Parameters
  • pred

    A predicate to determine which side the element belongs to.

  • filterable

    the list (or other filterable) to partition.

Returns Array An array, containing first the subset of elements that satisfy the predicate, and second the subset of elements that do not satisfy.

Added in v0.1.4

通过 predicate 将列表或 "Filterable" (可过滤的)对象分成两部分,分别为满足 predicate 的元素和不满足 predicate 的元素。元素类型保持不变。Filterable 类型包括 plain object 或者任何带有 filter 方法的类型,如 Array

See also filter, reject.
R.partition(R.includes('s'), ['sss', 'ttt', 'foo', 'bars']); // => [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ] R.partition(R.includes('s'), { a: 'sss', b: 'ttt', foo: 'bars' }); // => [ { a: 'sss', foo: 'bars' }, { b: 'ttt' } ]

path Object

[Idx] → {a} → a | Undefined
Idx = String | Int | Symbol
Parameters
  • path

    The path to use.

  • obj

    The object to retrieve the nested property from.

Returns * The data at `path`.

Added in v0.2.0

取出给定路径上的值。

See also prop, nth.
R.path(['a', 'b'], {a: {b: 2}}); //=> 2 R.path(['a', 'b'], {c: {b: 2}}); //=> undefined R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1 R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2

pathEq Relation

[Idx] → a → {a} → Boolean
Idx = String | Int | Symbol
Parameters
  • path

    The path of the nested property to use

  • val

    The value to compare the nested property with

  • obj

    The object to check the nested property in

Returns Boolean `true` if the value equals the nested object property, `false` otherwise.

Added in v0.7.0

判断对象的嵌套路径上是否为给定的值,通过 R.equals 函数进行相等性判断。常用于列表过滤。

const user1 = { address: { zipCode: 90210 } }; const user2 = { address: { zipCode: 55555 } }; const user3 = { name: 'Bob' }; const users = [ user1, user2, user3 ]; const isFamous = R.pathEq(['address', 'zipCode'], 90210); R.filter(isFamous, users); //=> [ user1 ]

pathOr Object

a → [Idx] → {a} → a
Idx = String | Int | Symbol
Parameters
  • d

    The default value.

  • p

    The path to use.

  • obj

    The object to retrieve the nested property from.

Returns * The data at `path` of the supplied object or the default value.

Added in v0.18.0

如果非空对象在给定路径上存在值,则将该值返回;否则返回给定的默认值。

R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2 R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A"

paths Object

[Idx] → {a} → [a | Undefined]
Idx = [String | Int | Symbol]
Parameters
  • pathsArray

    The array of paths to be fetched.

  • obj

    The object to retrieve the nested properties from.

Returns Array A list consisting of values at paths specified by "pathsArray".

Added in v0.27.1

提取对象中指定路径数组(paths)上的对应的值(values)

See also path.
R.paths([['a', 'b'], ['p', 0, 'q']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, 3] R.paths([['a', 'b'], ['p', 'r']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, undefined]

pathSatisfies Logic

(a → Boolean) → [Idx] → {a} → Boolean
Idx = String | Int | Symbol
Parameters
  • pred
  • propPath
  • obj
Returns Boolean

Added in v0.19.0

如果对象的给定路径上的属性满足 predicate,返回 ture;否则返回 false

See also propSatisfies, path.
R.pathSatisfies(y => y > 0, ['x', 'y'], {x: {y: 2}}); //=> true R.pathSatisfies(R.is(Object), [], {x: {y: 2}}); //=> true

pick Object

[k] → {k: v} → {k: v}
Parameters
  • names

    an array of String property names to copy onto a new object

  • obj

    The object to copy from

Returns Object A new object with only properties from `names` on it.

Added in v0.1.0

返回对象的部分拷贝,其中仅包含指定键对应的属性。如果某个键不存在,则忽略该属性。

See also omit, props.
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

[k] → {k: v} → {k: v}
Parameters
  • names

    an array of String property names to copy onto a new object

  • obj

    The object to copy from

Returns Object A new object with only properties from `names` on it.

Added in v0.1.0

pick 类似,但 pickAll 会将不存在的属性以 key: undefined 键值对的形式返回。

See also pick.
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

((v, k) → Boolean) → {k: v} → {k: v}
Parameters
  • pred

    A predicate to determine whether or not a key should be included on the output object.

  • obj

    The object to copy from

Returns Object A new object with only properties that satisfy `pred` on it.

Added in v0.8.0

返回对象的部分拷贝,其中仅包含 key 满足 predicate 的属性。

See also pick, filter.
const isUpperCase = (val, key) => key.toUpperCase() === key; R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}

pipe Function

(((a, b, …, n) → o), (o → p), …, (x → y), (y → z)) → ((a, b, …, n) → z)
Parameters
  • functions
Returns function

Added in v0.1.0

从左往右执行函数组合。第一个函数可以是任意元函数(参数个数不限),其余函数必须是一元函数。

在一些库中,此函数也被称为 sequence

** 注意:** pipe 函数的结果不是自动柯里化的。

See also compose.
const f = R.pipe(Math.pow, R.negate, R.inc); f(3, 4); // -(3^4) + 1

pipeWith Function

((* → *), [((a, b, …, n) → o), (o → p), …, (x → y), (y → z)]) → ((a, b, …, n) → z)
Parameters
  • transformer

    The transforming function

  • functions

    The functions to pipe

Returns function

Added in v0.26.0

利用转换函数从左往右执行函数组合。第一个函数可以是任意元函数(参数个数不限),其余函数必须是一元函数。

注意:pipe 输出的函数不会自动进行柯里化。

See also composeWith, pipe.
const pipeWhileNotNil = R.pipeWith((f, res) => R.isNil(res) ? res : f(res)); const f = pipeWhileNotNil([Math.pow, R.negate, R.inc]) f(3, 4); // -(3^4) + 1

pluck List

Functor f => k → f {k: v} → f v
Parameters
  • key

    The key name to pluck off of each object.

  • f

    The array or functor to consider.

Returns Array The list of values for the given key.

Added in v0.1.0

从列表内的每个对象元素中取出特定名称的属性,组成一个新的列表。

pluck 可以作用于任何 functor ,包括 Array,因为它等价于 R.map(R.prop(k), f)

See also project, prop, props.
var getAges = R.pluck('age'); getAges([{name: 'fred', age: 29}, {name: 'wilma', age: 27}]); //=> [29, 27] R.pluck(0, [[1, 2], [3, 4]]); //=> [1, 3] R.pluck('val', {a: {val: 3}, b: {val: 5}}); //=> {a: 3, b: 5}

prepend List

a → [a] → [a]
Parameters
  • el

    The item to add to the head of the output list.

  • list

    The array to add to the tail of the output list.

Returns Array A new array.

Added in v0.1.0

在列表头部之前拼接一个元素。

See also append.
R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum']

product Math

[Number] → Number
Parameters
  • list

    An array of numbers

Returns Number The product of all the numbers in the list.

Added in v0.1.0

列表中的所有元素相乘。

See also reduce.
R.product([2,4,6,8,100,1]); //=> 38400

project Object

[k] → [{k: v}] → [{k: v}]
Parameters
  • props

    The property names to project

  • objs

    The objects to query

Returns Array An array of objects with just the `props` properties.

Added in v0.1.0

模拟 SQL 中的 select 语句。

See also pluck, props, prop.
const abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}; const fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7}; const kids = [abby, fred]; R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}]

promap Function

(a → b) → (c → d) → (b → c) → (a → d)
Profunctor p => (a → b) → (c → d) → p b c → p a d
Parameters
  • f

    The preprocessor function, a -> b

  • g

    The postprocessor function, c -> d

  • profunctor

    The profunctor instance to be promapped, e.g. b -> c

Returns Profunctor The new profunctor instance, e.g. a -> d

Added in v0.28.0

接收两个函数分别在第三个函数执行前和执行后执行, 例如 promap(f, g, h)(x) === g(h(f(x)))

如果第三个参数有 promap 方法, 则执行, 根据 FantasyLand Profunctor spec

若在 profunctor 位置中给出 transfomer,则用作 transducer 。

See also transduce.
const decodeChar = R.promap(s => s.charCodeAt(), String.fromCharCode, R.add(-8)) const decodeString = R.promap(R.split(''), R.join(''), R.map(decodeChar)) decodeString("ziuli") //=> "ramda"

prop Object

Idx → {s: a} → a | Undefined
Idx = String | Int | Symbol
Parameters
  • p

    The property name or array index

  • obj

    The object to query

Returns * The value at `obj.p`.

Added in v0.1.0

取出对象中指定属性的值。如果不存在,则返回 undefined。

See also path, props, pluck, project, nth.
R.prop('x', {x: 100}); //=> 100 R.prop('x', {}); //=> undefined R.prop(0, [100]); //=> 100 R.compose(R.inc, R.prop('x'))({ x: 3 }) //=> 4

propEq Relation

String → a → Object → Boolean
Parameters
  • name
  • val
  • obj
Returns Boolean

Added in v0.1.0

如果指定对象属性与给定的值相等,则返回 true ;否则返回 false 。通过 R.equals 函数进行相等性判断。可以使用 R.whereEq 进行多个属性的相等性判断。

const abby = {name: 'Abby', age: 7, hair: 'blond'}; const fred = {name: 'Fred', age: 12, hair: 'brown'}; const rusty = {name: 'Rusty', age: 10, hair: 'brown'}; const alois = {name: 'Alois', age: 15, disposition: 'surly'}; const kids = [abby, fred, rusty, alois]; const hasBrownHair = R.propEq('hair', 'brown'); R.filter(hasBrownHair, kids); //=> [fred, rusty]

propIs Type

Type → String → Object → Boolean
Parameters
  • type
  • name
  • obj
Returns Boolean

Added in v0.16.0

判断指定对象的属性是否为给定的数据类型,是则返回 true ;否则返回 false

See also is, propSatisfies.
R.propIs(Number, 'x', {x: 1, y: 2}); //=> true R.propIs(Number, 'x', {x: 'foo'}); //=> false R.propIs(Number, 'x', {}); //=> false

propOr Object

a → String → Object → a
Parameters
  • val

    The default value.

  • p

    The name of the property to return.

  • obj

    The object to query.

Returns * The value of given property of the supplied object or the default value.

Added in v0.6.0

对于给定的非空对象,如果指定属性存在,则返回该属性值;否则返回给定的默认值。

const alice = { name: 'ALICE', age: 101 }; const favorite = R.prop('favoriteLibrary'); const favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary'); favorite(alice); //=> undefined favoriteWithDefault(alice); //=> 'Ramda'

props Object

[k] → {k: v} → [v]
Parameters
  • ps

    The property names to fetch

  • obj

    The object to query

Returns Array The corresponding values or partially applied function.

Added in v0.1.0

返回 prop 的数组:输入为 keys 数组,输出为对应的 values 数组。values 数组的顺序与 keys 的相同。

See also prop, pluck, project.
R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2] R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2] const fullName = R.compose(R.join(' '), R.props(['first', 'last'])); fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth'

propSatisfies Logic

(a → Boolean) → String → {String: a} → Boolean
Parameters
  • pred
  • name
  • obj
Returns Boolean

Added in v0.16.0

如果指定的对象属性满足 predicate,返回 true;否则返回 false。可以使用 R.where 进行多个属性的判断。

See also where, propEq, propIs.
R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true

range List

Number → Number → [Number]
Parameters
  • from

    The first number in the list.

  • to

    One more than the last number in the list.

Returns Array The list of numbers in the set `[a, b)`.

Added in v0.1.0

返回从 fromto 之间的所有数的升序列表。左闭右开(包含 from,不包含 to)。

R.range(1, 5); //=> [1, 2, 3, 4] R.range(50, 53); //=> [50, 51, 52]

reduce List

((a, b) → a) → a → [b] → a
Parameters
  • fn

    The iterator function. Receives two values, the accumulator and the current element from the array.

  • acc

    The accumulator value.

  • list

    The list to iterate over.

Returns * The final, accumulated value.

Added in v0.1.0

左折叠操作。

遍历列表,相继调用二元迭代函数(参数为累积值和从数组中取出的当前元素),将本次迭代结果作为下次迭代的累积值。返回最终累积值。

可以用 R.reduced 提前终止遍历操作。

reduce 的迭代函数接收两个参数 *(acc, value)*,reduceRight 的迭代函数的参数顺序为 (value, acc)

注意:R.reduce 与原生 Array.prototype.reduce 方法不同,它不会跳过删除或未分配的索引项(稀疏矩阵)。更多关于原生 reduce 的行为,请参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description

如果第三个参数自身有 reduce 方法,则调用自身的 reduce 方法。如果进行该步操作,则由用户自己来处理 R.reduced 短路操作,因为自身 reduce 方法的实现可能与 Ramda 中的 reduce 不同。

R.reduce(R.subtract, 0, [1, 2, 3, 4]) // => ((((0 - 1) - 2) - 3) - 4) = -10 // - -10 // / \ / \ // - 4 -6 4 // / \ / \ // - 3 ==> -3 3 // / \ / \ // - 2 -1 2 // / \ / \ // 0 1 0 1

reduceBy List

((a, b) → a) → a → (b → String) → [b] → {String: a}
Parameters
  • valueFn

    The function that reduces the elements of each group to a single value. Receives two values, accumulator for a particular group and the current element.

  • acc

    The (initial) accumulator value for each group.

  • keyFn

    The function that maps the list's element into a key.

  • list

    The array to group.

Returns Object An object with the output of `keyFn` for keys, mapped to the output of `valueFn` for elements which produced that key when passed to `keyFn`.

Added in v0.20.0

首先对列表中的每个元素调用函数 keyFn ,根据 keyFn 返回的字符串对列表元素进行分组。然后调用 reducer 函数 valueFn,对组内的元素进行折叠操作。

该函数相当于更通用的 groupBy 函数。

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装。

See also groupBy, reduce, reduced.
const groupNames = (acc, {name}) => acc.concat(name) const toGrade = ({score}) => score < 65 ? 'F' : score < 70 ? 'D' : score < 80 ? 'C' : score < 90 ? 'B' : 'A' var students = [ {name: 'Abby', score: 83}, {name: 'Bart', score: 62}, {name: 'Curt', score: 88}, {name: 'Dora', score: 92}, ] reduceBy(groupNames, [], toGrade, students) //=> {"A": ["Dora"], "B": ["Abby", "Curt"], "F": ["Bart"]}

reduced List

a → *
Parameters
  • x

    The final value of the reduce.

Returns * The wrapped value.

Added in v0.15.0

返回一个封装的值,该值代表 reducetransduce 操作的最终结果。

返回值是一个黑盒:不保证其内部结构的稳定性。

注意:这个优化不适用于上面未明确列出的函数。例如,现在还不支持 reduceRight

R.reduce( (acc, item) => item > 3 ? R.reduced(acc) : acc.concat(item), [], [1, 2, 3, 4, 5]) // [1, 2, 3]

reduceRight List

((a, b) → b) → b → [a] → b
Parameters
  • fn

    The iterator function. Receives two values, the current element from the array and the accumulator.

  • acc

    The accumulator value.

  • list

    The list to iterate over.

Returns * The final, accumulated value.

Added in v0.1.0

右折叠操作。

遍历列表,相继调用二元迭代函数(参数为累积值和从数组中取出的当前元素),将本次迭代结果作为下次迭代的累积值。返回最终累积值。

类似于 reduce,除了遍历列表的顺序是从右向左的。

reduceRight 的迭代函数接收两个参数 *(value, acc)*。与之对应的,reduce 的迭代函数的参数顺序为 (acc, value)

注意:R.reduceRight 与原生 Array.prototype.reduceRight 方法不同,它不会跳过删除或未分配的索引项(稀疏矩阵)。更多关于原生 reduceRight 的行为,请参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description

See also reduce, addIndex, reduced.
R.reduceRight(R.subtract, 0, [1, 2, 3, 4]) // => (1 - (2 - (3 - (4 - 0)))) = -2 // - -2 // / \ / \ // 1 - 1 3 // / \ / \ // 2 - ==> 2 -1 // / \ / \ // 3 - 3 4 // / \ / \ // 4 0 4 0

reduceWhile List

((a, b) → Boolean) → ((a, b) → a) → a → [b] → a
Parameters
  • pred

    The predicate. It is passed the accumulator and the current element.

  • fn

    The iterator function. Receives two values, the accumulator and the current element.

  • a

    The accumulator value.

  • list

    The list to iterate over.

Returns * The final, accumulated value.

Added in v0.22.0

reduce 类似, reduceWhile 会遍历列表,相继调用二元迭代函数,并返回最终累积值。reduceWhile 在每次调用迭代函数前,先使用 predicate 进行判断,如果 predicate 返回 false ,则提前终止遍历操作,并返回当前累积值。

See also reduce, reduced.
const isOdd = (acc, x) => x % 2 !== 0; const xs = [1, 3, 5, 60, 777, 800]; R.reduceWhile(isOdd, R.add, 0, xs); //=> 9 const ys = [2, 4, 6] R.reduceWhile(isOdd, R.add, 111, ys); //=> 111

reject List

Filterable f => (a → Boolean) → f a → f a
Parameters
  • pred
  • filterable
Returns Array

Added in v0.1.0

filter 的补操作。返回结果为 R.filter 操作结果的补集。

若在列表位置给出 transformer,则用作 transducer。Filterable 类型包括 plain object 或者任何带有 filter 方法的类型,如 Array

See also filter, transduce, addIndex.
const isOdd = (n) => n % 2 !== 0; R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] R.reject(isOdd, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4}

remove List

Number → Number → [a] → [a]
Parameters
  • start

    The position to start removing elements

  • count

    The number of elements to remove

  • list

    The list to remove from

Returns Array A new Array with `count` elements from `start` removed.

Added in v0.2.2

删除列表中从 start 开始的 count 个元素。注意,该操作是非破坏性的:不改变原列表,返回处理后列表的拷贝。

See also without.
R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8]

repeat List

a → n → [a]
Parameters
  • value

    The value to repeat.

  • n

    The desired size of the output list.

Returns Array A new array containing `n` `value`s.

Added in v0.1.1

生成包含 n 个同一元素的数组。

See also times.
R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi'] const obj = {}; const repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}] repeatedObjs[0] === repeatedObjs[1]; //=> true

replace String

RegExp|String → String → String → String
Parameters
  • pattern

    A regular expression or a substring to match.

  • replacement

    The string to replace the matches with.

  • str

    The String to do the search and replacement in.

Returns String The result.

Added in v0.7.0

替换字符串的子串或正则匹配到的值。

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

[a] → [a]
String → String
Parameters
  • list
Returns Array

Added in v0.1.0

对列表或字符串的排列顺序取反。

R.reverse([1, 2, 3]); //=> [3, 2, 1] R.reverse([1, 2]); //=> [2, 1] R.reverse([1]); //=> [1] R.reverse([]); //=> [] R.reverse('abc'); //=> 'cba' R.reverse('ab'); //=> 'ba' R.reverse('a'); //=> 'a' R.reverse(''); //=> ''

scan List

((a, b) → a) → a → [b] → [a]
Parameters
  • fn

    The iterator function. Receives two values, the accumulator and the current element from the array

  • acc

    The accumulator value.

  • list

    The list to iterate over.

Returns Array A list of all intermediately reduced values.

Added in v0.10.0

Scan 与 reduce 类似,但会将每次迭代计算的累积值记录下来,组成一个列表返回。

See also reduce, mapAccum.
const numbers = [1, 2, 3, 4]; const factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24]

sequence List

(Applicative f, Traversable t) => (a → f a) → t (f a) → f (t a)
Parameters
  • of
  • traversable
Returns *

Added in v0.19.0

将一个 ApplicativeTraversable 转换成一个 Traversable 类型的 Applicative。

如果第二个参数自身存在 sequence 方法,则调用自身的 sequence

See also traverse.
R.sequence(Maybe.of, [Just(1), Just(2), Just(3)]); //=> Just([1, 2, 3]) R.sequence(Maybe.of, [Just(1), Just(2), Nothing()]); //=> Nothing() R.sequence(R.of, Just([1, 2, 3])); //=> [Just(1), Just(2), Just(3)] R.sequence(R.of, Nothing()); //=> [Nothing()]

set Object

Lens s a → a → s → s
Lens s a = Functor f => (a → f a) → s → f s
Parameters
  • lens
  • v
  • x
Returns *

Added in v0.16.0

通过 lens 对数据结构聚焦的部分进行设置。

const xLens = R.lensProp('x'); R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} R.set(xLens, 8, {x: 1, y: 2}); //=> {x: 8, y: 2}

slice List

Number → Number → [a] → [a]
Number → Number → String → String
Parameters
  • fromIndex

    The start index (inclusive).

  • toIndex

    The end index (exclusive).

  • list
Returns *

Added in v0.1.4

取出给定的列表或字符串(或带有 slice 方法的对象)中,从 fromIndex(包括)到 toIndex(不包括)的元素。

如果第三个参数自身存在 slice 方法,则调用自身的 slice 方法。

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

((a, a) → Number) → [a] → [a]
Parameters
  • comparator

    A sorting function :: a -> b -> Int

  • list

    The list to sort

Returns Array a new array with its elements sorted by the comparator function.

Added in v0.1.0

使用比较函数对列表进行排序。比较函数每次接受两个参数,如果第一个值较小,则返回负数;如果第一个值较大,则返回正数;如果两值相等,返回零。注意,返回的是列表的 ** 拷贝 ** ,不会修改原列表。

See also ascend, descend.
const diff = function(a, b) { return a - b; }; R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7]

sortBy Relation

Ord b => (a → b) → [a] → [a]
Parameters
  • fn
  • list

    The list to sort.

Returns Array A new list sorted by the keys generated by `fn`.

Added in v0.1.0

根据给定的函数对列表进行排序。

const sortByFirstItem = R.sortBy(R.prop(0)); const pairs = [[-1, 1], [-2, 2], [-3, 3]]; sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]] const sortByNameCaseInsensitive = R.sortBy(R.compose(R.toLower, R.prop('name'))); const alice = { name: 'ALICE', age: 101 }; const bob = { name: 'Bob', age: -10 }; const clara = { name: 'clara', age: 314.159 }; const people = [clara, bob, alice]; sortByNameCaseInsensitive(people); //=> [alice, bob, clara]

sortWith Relation

[(a, a) → Number] → [a] → [a]
Parameters
  • functions

    A list of comparator functions.

  • list

    The list to sort.

Returns Array A new list sorted according to the comarator functions.

Added in v0.23.0

依据比较函数列表对输入列表进行排序。

See also ascend, descend.
const alice = { name: 'alice', age: 40 }; const bob = { name: 'bob', age: 30 }; const clara = { name: 'clara', age: 40 }; const people = [clara, bob, alice]; const ageNameSort = R.sortWith([ R.descend(R.prop('age')), R.ascend(R.prop('name')) ]); ageNameSort(people); //=> [alice, clara, bob]

split String

(String | RegExp) → String → [String]
Parameters
  • sep

    The pattern.

  • str

    The string to separate into an array.

Returns Array The array of strings from `str` separated by `sep`.

Added in v0.1.0

根据指定的分隔符将字符串拆分为字符串类型的数组。

See also join.
const 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']

splitAt List

Number → [a] → [[a], [a]]
Number → String → [String, String]
Parameters
  • index

    The index where the array/string is split.

  • array

    The array/string to be split.

Returns Array

Added in v0.19.0

在指定的索引处拆分列表或者字符串。

R.splitAt(1, [1, 2, 3]); //=> [[1], [2, 3]] R.splitAt(5, 'hello world'); //=> ['hello', ' world'] R.splitAt(-1, 'foobar'); //=> ['fooba', 'r']

splitEvery List

Number → [a] → [[a]]
Number → String → [String]
Parameters
  • n
  • list
Returns Array

Added in v0.16.0

将列表拆分成指定长度的子列表集。

R.splitEvery(3, [1, 2, 3, 4, 5, 6, 7]); //=> [[1, 2, 3], [4, 5, 6], [7]] R.splitEvery(3, 'foobarbaz'); //=> ['foo', 'bar', 'baz']

splitWhen List

(a → Boolean) → [a] → [[a], [a]]
Parameters
  • pred

    The predicate that determines where the array is split.

  • list

    The array to be split.

Returns Array

Added in v0.19.0

查找列表中首个满足 predicate 的元素,在该处将列表拆分为两部分。首个满足 predicate 的元素包含在后一部分。

R.splitWhen(R.equals(2), [1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]]

splitWhenever List

(a → Boolean) → [a] → [[a]]
Parameters
  • pred

    The predicate that determines where the array is split.

  • list

    The array to be split.

Returns Array

Added in v0.26.1

根据列表中每个元素是否满足 predicate 来拆分数组。

R.splitWhenever(R.equals(2), [1, 2, 3, 2, 4, 5, 2, 6, 7]); //=> [[1], [3], [4, 5], [6, 7]]

startsWith List

[a] → [a] → Boolean
String → String → Boolean
Parameters
  • prefix
  • list
Returns Boolean

Added in v0.24.0

检查列表是否以给定的值开头。

See also endsWith.
R.startsWith('a', 'abc') //=> true R.startsWith('b', 'abc') //=> false R.startsWith(['a'], ['a', 'b', 'c']) //=> true R.startsWith(['b'], ['a', 'b', 'c']) //=> false

subtract Math

Number → Number → Number
Parameters
  • a

    The first value.

  • b

    The second value.

Returns Number The result of `a - b`.

Added in v0.1.0

首个参数减去第二个参数。

See also add.
R.subtract(10, 8); //=> 2 const minus5 = R.subtract(R.__, 5); minus5(17); //=> 12 const complementaryAngle = R.subtract(90); complementaryAngle(30); //=> 60 complementaryAngle(72); //=> 18

sum Math

[Number] → Number
Parameters
  • list

    An array of numbers

Returns Number The sum of all the numbers in the list.

Added in v0.1.0

对数组中所有元素求和。

See also reduce.
R.sum([2,4,6,8,100,1]); //=> 121

symmetricDifference Relation

[*] → [*] → [*]
Parameters
  • list1

    The first list.

  • list2

    The second list.

Returns Array The elements in `list1` or `list2`, but not both.

Added in v0.19.0

求对称差集。所有不属于两列表交集元素的集合,其元素在且仅在给定列表中的一个里面出现。

R.symmetricDifference([1,2,3,4], [7,6,5,4,3]); //=> [1,2,7,6,5] R.symmetricDifference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5,1,2]

symmetricDifferenceWith Relation

((a, a) → Boolean) → [a] → [a] → [a]
Parameters
  • pred

    A predicate used to test whether two items are equal.

  • list1

    The first list.

  • list2

    The second list.

Returns Array The elements in `list1` or `list2`, but not both.

Added in v0.19.0

求对称差集。所有不属于两列表交集元素的集合。交集的元素由条件函数的返回值决定。

const eqA = R.eqBy(R.prop('a')); const l1 = [{a: 1}, {a: 2}, {a: 3}, {a: 4}]; const l2 = [{a: 3}, {a: 4}, {a: 5}, {a: 6}]; R.symmetricDifferenceWith(eqA, l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}]

T Function

* → Boolean
Parameters
Returns Boolean

Added in v0.9.0

恒定返回 true 的函数。忽略所有的输入参数。

See also F.
R.T(); //=> true

tail List

[a] → [a]
String → String
Parameters
  • list
Returns *

Added in v0.1.0

删除列表中的首个元素(或者调用对象的 tail 方法)。

如果第一个参数自身存在 slice 方法,则调用自身的 slice 方法。

See also head, init, last.
R.tail([1, 2, 3]); //=> [2, 3] R.tail([1, 2]); //=> [2] R.tail([1]); //=> [] R.tail([]); //=> [] R.tail('abc'); //=> 'bc' R.tail('ab'); //=> 'b' R.tail('a'); //=> '' R.tail(''); //=> ''

take List

Number → [a] → [a]
Number → String → String
Parameters
  • n
  • list
Returns *

Added in v0.1.0

返回列表的前 n 个元素、字符串的前n个字符或者用作 transducer/transform(或者调用对象的 take 方法)。

如果第二个参数自身存在 take 方法,则调用自身的 take 方法。

See also drop.
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' const personnel = [ 'Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan', 'Bob Bates', 'Joe Dodge', 'Ron Crotty' ]; const takeFive = R.take(5); takeFive(personnel); //=> ['Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan']

takeLast List

Number → [a] → [a]
Number → String → String
Parameters
  • n

    The number of elements to return.

  • xs

    The collection to consider.

Returns Array

Added in v0.16.0

返回列表的后 n 个元素。如果 n > list.length,则返回 list.length 个元素。

See also dropLast.
R.takeLast(1, ['foo', 'bar', 'baz']); //=> ['baz'] R.takeLast(2, ['foo', 'bar', 'baz']); //=> ['bar', 'baz'] R.takeLast(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] R.takeLast(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] R.takeLast(3, 'ramda'); //=> 'mda'

takeLastWhile List

(a → Boolean) → [a] → [a]
(a → Boolean) → String → String
Parameters
  • fn

    The function called per iteration.

  • xs

    The collection to iterate over.

Returns Array A new array.

Added in v0.16.0

从后往前取出列表元素,直到遇到首个不满足 predicate 的元素为止。取出的元素中不包含首个不满足 predicate 的元素。

See also dropLastWhile, addIndex.
const isNotOne = x => x !== 1; R.takeLastWhile(isNotOne, [1, 2, 3, 4]); //=> [2, 3, 4] R.takeLastWhile(x => x !== 'R' , 'Ramda'); //=> 'amda'

takeWhile List

(a → Boolean) → [a] → [a]
(a → Boolean) → String → String
Parameters
  • fn

    The function called per iteration.

  • xs

    The collection to iterate over.

Returns Array A new array.

Added in v0.1.0

从前往后取出列表元素,直到遇到首个不满足 predicate 的元素为止。取出的元素中不包含首个不满足 predicate 的元素。

若第二个参数自身存在 takeWhile 方法,则调用自身的 takeWhile 方法

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装 。

const isNotFour = x => x !== 4; R.takeWhile(isNotFour, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3] R.takeWhile(x => x !== 'd' , 'Ramda'); //=> 'Ram'

tap Function

(a → *) → a → a
Parameters
  • fn

    The function to call with x. The return value of fn will be thrown away.

  • x
Returns * `x`.

Added in v0.1.0

对输入的值执行给定的函数,然后返回输入的值。

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装。

const sayX = x => console.log('x is ' + x); R.tap(sayX, 100); //=> 100 // logs 'x is 100'

test String

RegExp → String → Boolean
Parameters
  • pattern
  • str
Returns Boolean

Added in v0.12.0

检测字符串是否匹配给定的正则表达式。

See also match.
R.test(/^x/, 'xyz'); //=> true R.test(/^y/, 'xyz'); //=> false

thunkify Function

((a, b, …, j) → k) → (a, b, …, j) → (() → k)
Parameters
  • fn

    A function to wrap in a thunk

Returns function Expects arguments for `fn` and returns a new function that, when called, applies those arguments to `fn`.

Added in v0.26.0

创建一个 thunk 版本的函数。 thunk 会延迟计算直到需要其结果,从而实现惰性求值。

See also partial, partialRight.
R.thunkify(R.identity)(42)(); //=> 42 R.thunkify((a, b) => a + b)(25, 17)(); //=> 42

times List

(Number → a) → Number → [a]
Parameters
  • fn

    The function to invoke. Passed one argument, the current value of n.

  • n

    A value between 0 and n - 1. Increments after each function call.

Returns Array An array containing the return values of all calls to `fn`.

Added in v0.2.3

执行输入的函数 n 次,返回由函数执行结果组成的数组。

fn 为一元函数,n 次调用接收的参数为:从 0 递增到 n-1

See also repeat.
R.times(R.identity, 5); //=> [0, 1, 2, 3, 4]

toLower String

String → String
Parameters
  • str

    The string to lower case.

Returns String The lower case version of `str`.

Added in v0.9.0

将字符串转换成小写。

See also toUpper.
R.toLower('XYZ'); //=> 'xyz'

toPairs Object

{String: *} → [[String,*]]
Parameters
  • obj

    The object to extract from

Returns Array An array of key, value arrays from the object's own properties.

Added in v0.4.0

将一个对象的属性转换成键、值二元组类型的数组,只处理对象自身的属性。注意:不同 JS 运行环境输出数组的顺序可能不一致。

See also fromPairs, keys, values.
R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]]

toPairsIn Object

{String: *} → [[String,*]]
Parameters
  • obj

    The object to extract from

Returns Array An array of key, value arrays from the object's own and prototype properties.

Added in v0.4.0

将一个对象的属性转换成键、值二元组类型的数组,包括原型链上的属性。注意,不同 JS 运行环境输出数组的顺序可能不一致。

const F = function() { this.x = 'X'; }; F.prototype.y = 'Y'; const f = new F(); R.toPairsIn(f); //=> [['x','X'], ['y','Y']]

toString String

* → String
Parameters
  • val
Returns String

Added in v0.14.0

返回代表输入元素的字符串。求得的输出结果应该等价于输入的值。许多内建的 toString 方法都不满足这一条件。

如果输入值是 [object Object] 对象,且自身含有 toString 方法(不是 Object.prototype.toString 方法),那么直接调用这个方法求返回值。这意味着,通过用户自定义的构造函数可以提供合适的 toString 方法。例如:

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 → String
Parameters
  • str

    The string to upper case.

Returns String The upper case version of `str`.

Added in v0.9.0

将字符串转换为大写。

See also toLower.
R.toUpper('abc'); //=> 'ABC'

transduce List

(c → c) → ((a, b) → a) → a → [b] → a
Parameters
  • xf

    The transducer function. Receives a transformer and returns a transformer.

  • 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.

  • list

    The list to iterate over.

Returns * The final, accumulated value.

Added in v0.12.0

用 iterator function 初始化 transducer ,生成一个 transformed iterator function。然后顺次遍历列表,对每个列表元素先进行转换,然后与累积值进行归约,返回值作为下一轮迭代的累积值。最终返回与初始累积值类型相同的一个累积值。

iterator function 接收两个参数: (acc, value) ,iterator function 会被封装为 transformer 来初始化 transducer 。可以直接传递 transformer 来代替 iterator function。这两种情况下,可以使用 R.reduced 提前终止迭代操作。

transducer 函数接受一个 transformer ,返回一个新的 transformer ,并且 transducer 函数可以直接组合。

transformer 是一个对象,其中包含二元 reducing iterator、step、零元 init 和 一元 result 函数。step 作为 reduce 过程中的迭代函数;result 将最终的累积值转换为需要的返回类型(通常为 R.identity );init 提供初始累积值,但通常会被 transduce 函数忽略。

在 transducer 初始化之后,使用 R.reduce 进行迭代操作。

See also reduce, reduced, into.
const numbers = [1, 2, 3, 4]; const transducer = R.compose(R.map(R.add(1)), R.take(2)); R.transduce(transducer, R.flip(R.append), [], numbers); //=> [2, 3] const isOdd = (x) => x % 2 !== 0; const firstOddTransducer = R.compose(R.filter(isOdd), R.take(1)); R.transduce(firstOddTransducer, R.flip(R.append), [], R.range(0, 100)); //=> [1]

transpose List

[[a]] → [[a]]
Parameters
  • list

    A 2D list

Returns Array A 2D list

Added in v0.19.0

二维数组行列转置。输入 n 个长度为 x 的数组,输出 x 个长度为 n 的数组。

R.transpose([[1, 'a'], [2, 'b'], [3, 'c']]) //=> [[1, 2, 3], ['a', 'b', 'c']] R.transpose([[1, 2, 3], ['a', 'b', 'c']]) //=> [[1, 'a'], [2, 'b'], [3, 'c']] // If some of the rows are shorter than the following rows, their elements are skipped: R.transpose([[10, 11], [20], [], [30, 31, 32]]) //=> [[10, 20, 30], [11, 31], [32]]

traverse List

(Applicative f, Traversable t) => (a → f a) → (a → f b) → t a → f (t b)
Parameters
  • of
  • f
  • traversable
Returns *

Added in v0.19.0

将返回值为 Applicative 类型的函数映射到一个 Traversable 上。然后使用 sequence 将结果由 Traversable of Applicative 转换为 Applicative of Traversable。

若第三个参数自身存在 traverse 方法,则调用自身的 traverse 方法。

See also sequence.
// Returns `Maybe.Nothing` if the given divisor is `0` const safeDiv = n => d => d === 0 ? Maybe.Nothing() : Maybe.Just(n / d) R.traverse(Maybe.of, safeDiv(10), [2, 4, 5]); //=> Maybe.Just([5, 2.5, 2]) R.traverse(Maybe.of, safeDiv(10), [2, 0, 5]); //=> Maybe.Nothing

trim String

String → String
Parameters
  • str

    The string to trim.

Returns String Trimmed version of `str`.

Added in v0.6.0

删除字符串首、尾两端的空白字符。

R.trim(' xyz '); //=> 'xyz' R.map(R.trim, R.split(',', 'x, y, z')); //=> ['x', 'y', 'z']

tryCatch Function

(…x → a) → ((e, …x) → a) → (…x → a)
Parameters
  • tryer

    The function that may throw.

  • catcher

    The function that will be evaluated if tryer throws.

Returns function A new function that will catch exceptions and send them to the catcher.

Added in v0.20.0

tryCatch 接受两个函数:tryercatcher,生成的函数执行 tryer,若未抛出异常,则返回执行结果。若抛出异常,则执行 catcher,返回 catcher 的执行结果。注意,为了有效的组合该函数,tryercatcher 应返回相同类型的值。

R.tryCatch(R.prop('x'), R.F)({x: true}); //=> true R.tryCatch(() => { throw 'foo'}, R.always('caught'))('bar') // => 'caught' R.tryCatch(R.times(R.identity), R.always([]))('s') // => [] R.tryCatch(() => { throw 'this is not a valid value'}, (err, value)=>({error : err, value }))('bar') // => {'error': 'this is not a valid value', 'value': 'bar'}

type Type

(* → {*}) → String
Parameters
  • val

    The value to test

Returns String

Added in v0.8.0

用一个单词来描述输入值的(原生)类型,返回诸如 'Object'、'Number'、'Array'、'Null' 之类的结果。不区分用户自定义的类型,统一返回 '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" R.type(() => {}); //=> "Function" R.type(undefined); //=> "Undefined"

unapply Function

([*…] → a) → (*… → a)
Parameters
  • fn
Returns function

Added in v0.8.0

输入一个只接收单个数组作为参数的函数,返回一个新函数:

  • 接收任意个参数;
  • 将参数组成数组传递给 fn
  • 返回执行结果。

换言之,R.unapply 将一个使用数组作为参数的函数,变为一个不定参函数。 R.unapplyR.apply 的逆函数。

See also apply.
R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]'

unary Function

(a → b → c → … → z) → (a → z)
Parameters
  • fn

    The function to wrap.

Returns function A new function wrapping `fn`. The new function is guaranteed to be of arity 1.

Added in v0.2.0

将任意元(包括零元)函数封装成一元函数。任何额外的参数都不会传递给被封装的函数。

See also binary, nAry.
const takesTwoArgs = function(a, b) { return [a, b]; }; takesTwoArgs.length; //=> 2 takesTwoArgs(1, 2); //=> [1, 2] const takesOneArg = R.unary(takesTwoArgs); takesOneArg.length; //=> 1 // Only 1 argument is passed to the wrapped function takesOneArg(1, 2); //=> [1, undefined]

uncurryN Function

Number → (a → b → c … → z) → ((a → b → c …) → z)
Parameters
  • length

    The arity for the returned function.

  • fn

    The function to uncurry.

Returns function A new function.

Added in v0.14.0

将一个柯里化的函数转换为一个 n 元函数。

See also curry, curryN.
const addFour = a => b => c => d => a + b + c + d; const uncurriedAddFour = R.uncurryN(4, addFour); uncurriedAddFour(1, 2, 3, 4); //=> 10

unfold List

(a → [b]) → * → [b]
Parameters
  • 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 to fn.

  • seed

    The seed value.

Returns Array The final list.

Added in v0.10.0

通过一个种子值( seed )创建一个列表。unfold 接受一个迭代函数:该函数或者返回 false 停止迭代,或者返回一个长度为 2 的数组:数组首个元素添加到结果列表,第二个元素作为种子值传给下一轮迭代使用。

迭代函数接受单个参数: *(seed)*。

const f = n => n > 50 ? false : [-n, n + 10]; R.unfold(f, 10); //=> [-10, -20, -30, -40, -50]

union Relation

[*] → [*] → [*]
Parameters
  • as

    The first list.

  • bs

    The second list.

Returns Array The first and second lists concatenated, with duplicates removed.

Added in v0.1.0

集合并运算,合并两个列表为新列表(新列表中无重复元素)。

R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4]

unionWith Relation

((a, a) → Boolean) → [*] → [*] → [*]
Parameters
  • pred

    A predicate used to test whether two items are equal.

  • list1

    The first list.

  • list2

    The second list.

Returns Array The first and second lists concatenated, with duplicates removed.

Added in v0.1.0

集合并运算,合并两个列表为新列表(新列表中无重复元素)。由 predicate 的返回值决定两元素是否重复。

See also union.
const l1 = [{a: 1}, {a: 2}]; const l2 = [{a: 1}, {a: 4}]; R.unionWith(R.eqBy(R.prop('a')), l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}]

uniq List

[a] → [a]
Parameters
  • list

    The array to consider.

Returns Array The list of unique items.

Added in v0.1.0

列表去重操作。返回无重复元素的列表。通过 R.equals 函数进行相等性判断。

R.uniq([1, 1, 2, 1]); //=> [1, 2] R.uniq([1, '1']); //=> [1, '1'] R.uniq([[42], [42]]); //=> [[42]]

uniqBy List

(a → b) → [a] → [a]
Parameters
  • fn

    A function used to produce a value to use during comparisons.

  • list

    The array to consider.

Returns Array The list of unique items.

Added in v0.16.0

返回无重复元素的列表。元素通过给定的函数的返回值以及 R.equals 进行相同性判断。如果给定的函数返回值相同,保留第一个元素。

R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10]

uniqWith List

((a, a) → Boolean) → [a] → [a]
Parameters
  • pred

    A predicate used to test whether two items are equal.

  • list

    The array to consider.

Returns Array The list of unique items.

Added in v0.2.0

返回无重复元素的列表。元素通过 predicate 进行相同性判断。如果通过 predicate 判断两元素相同,保留第一个元素。

const strEq = R.eqBy(String); 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']

unless Logic

(a → Boolean) → (a → b) → a → a | b
Parameters
  • pred

    A predicate function

  • whenFalseFn

    A function to invoke when the pred evaluates to a falsy value.

  • x

    An object to test with the pred function and pass to whenFalseFn if necessary.

Returns * Either `x` or the result of applying `x` to `whenFalseFn`.

Added in v0.18.0

判断输入值是否满足 predicate,若不符合,则将输入值传给 whenFalseFn 处理,并将处理结果作为返回;若符合,则将输入值原样返回。

See also ifElse, when, cond.
let safeInc = R.unless(R.isNil, R.inc); safeInc(null); //=> null safeInc(1); //=> 2

unnest List

Chain c => c (c a) → c a
Parameters
  • list
Returns *

Added in v0.3.0

R.chain(R.identity) 的简写, 对 Chain 类型的数据消除一层嵌套.

See also flatten, chain.
R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]] R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6]

until Logic

(a → Boolean) → (a → a) → a → a
Parameters
  • pred

    A predicate function

  • fn

    The iterator function

  • init

    Initial value

Returns * Final value that satisfies predicate

Added in v0.20.0

接受一个 predicate ,transform function 和 初始值,返回一个与初始值相同类型的值。对输入值进行 transform ,直到 transform 的结果满足 predicate,此时返回这个满足 predicate 的值。

R.until(R.gt(R.__, 100), R.multiply(2))(1) // => 128

unwind Object

String → {k: [v]} → [{k: v}]
Parameters
  • key

    The key to determine which property of the object should be unwind

  • object

    The object containing list under property named as key which is to unwind

Returns List A new list of object containing the value of input key having list replaced by each element in the object.

Added in v0.28.0

如果指定属性的值为数组,其结果为相同顺序的对象数组,对象里指定属性的值被数组对应元素替换,其余属性和原对象属性一致。

R.unwind('hobbies', { name: 'alice', hobbies: ['Golf', 'Hacking'], colors: ['red', 'green'], }); // [ // { name: 'alice', hobbies: 'Golf', colors: ['red', 'green'] }, // { name: 'alice', hobbies: 'Hacking', colors: ['red', 'green'] } // ]

update List

Number → a → [a] → [a]
Parameters
  • idx

    The index to update.

  • x

    The value to exist at the given index of the returned array.

  • list

    The source array-like object to be updated.

Returns Array A copy of `list` with the value at index `idx` replaced with `x`.

Added in v0.14.0

替换数组中指定索引处的值。

See also adjust.
R.update(1, '_', ['a', 'b', 'c']); //=> ['a', '_', 'c'] R.update(-1, '_', ['a', 'b', 'c']); //=> ['a', 'b', '_']

useWith Function

((x1, x2, …) → z) → [(a → x1), (b → x2), …] → (a → b → … → z)
Parameters
  • fn

    The function to wrap.

  • transformers

    A list of transformer functions

Returns function The wrapped function.

Added in v0.1.0

接受一个函数 fn 和一个 transformer 函数的列表,返回一个柯里化的新函数。当被调用时,新函数将每个参数转发给对应位置的 transformer 函数,然后将每个 transformer 函数的计算结果作为参数传递给 fnfn 的计算结果即新函数的返回值。

如果新函数传传入参数的数量比 transformer 函数的数量多,多出的参数会作为附加参数直接传给 fn 。如果不需要处理多出的那部分参数,除了忽略之外,也可以用 identity 函数来作为 transformer ,以保证新函数的参数数量是确定的。

See also converge.
R.useWith(Math.pow, [R.identity, R.identity])(3, 4); //=> 81 R.useWith(Math.pow, [R.identity, R.identity])(3)(4); //=> 81 R.useWith(Math.pow, [R.dec, R.inc])(3, 4); //=> 32 R.useWith(Math.pow, [R.dec, R.inc])(3)(4); //=> 32

values Object

{k: v} → [v]
Parameters
  • obj

    The object to extract values from

Returns Array An array of the values of the object's own properties.

Added in v0.1.0

返回对象所有自身可枚举的属性的值。注意:不同 JS 运行环境输出数组的顺序可能不一致。

See also valuesIn, keys, toPairs.
R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3]

valuesIn Object

{k: v} → [v]
Parameters
  • obj

    The object to extract values from

Returns Array An array of the values of the object's own and prototype properties.

Added in v0.2.0

返回对象所有属性的值,包括原型链上的属性。注意:不同 JS 运行环境输出数组的顺序可能不一致。

See also values, keysIn.
const F = function() { this.x = 'X'; }; F.prototype.y = 'Y'; const f = new F(); R.valuesIn(f); //=> ['X', 'Y']

view Object

Lens s a → s → a
Lens s a = Functor f => (a → f a) → s → f s
Parameters
  • lens
  • x
Returns *

Added in v0.16.0

返回数据结构中,lens 聚焦的部分。lens 的焦点决定了数据结构中的哪部分是可见的。

const xLens = R.lensProp('x'); R.view(xLens, {x: 1, y: 2}); //=> 1 R.view(xLens, {x: 4, y: 2}); //=> 4

when Logic

(a → Boolean) → (a → b) → a → a | b
Parameters
  • pred

    A predicate function

  • whenTrueFn

    A function to invoke when the condition evaluates to a truthy value.

  • x

    An object to test with the pred function and pass to whenTrueFn if necessary.

Returns * Either `x` or the result of applying `x` to `whenTrueFn`.

Added in v0.18.0

判断输入值是否满足 predicate,若符合,则将输入值传给 whenTrueFn 处理,并将处理结果作为返回;若不符合,则将输入值原样返回。

See also ifElse, unless, cond.
// truncate :: String -> String const truncate = R.when( R.propSatisfies(R.gt(R.__, 10), 'length'), R.pipe(R.take(10), R.append('…'), R.join('')) ); truncate('12345'); //=> '12345' truncate('0123456789ABC'); //=> '0123456789…'

where Object

{String: (* → Boolean)} → {String: *} → Boolean
Parameters
  • spec
  • testObj
Returns Boolean

Added in v0.1.1

接受一个测试规范对象和一个待检测对象,如果测试满足规范,则返回 true,否则返回 false。测试规范对象的每个属性值都必须是 predicate 。每个 predicate 作用于待检测对象对应的属性值,如果所有 predicate 都返回 true,则 where 返回 true,否则返回 false 。

where 非常适合于需要声明式表示约束的函数,比如 filterfind

See also propSatisfies, whereEq.
// pred :: Object -> Boolean const pred = R.where({ a: R.equals('foo'), b: R.complement(R.equals('bar')), x: R.gt(R.__, 10), y: R.lt(R.__, 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

whereAny Object

{String: (* → Boolean)} → {String: *} → Boolean
Parameters
  • spec
  • testObj
Returns Boolean

Added in v0.28.0

接受一个测试规范对象和一个待检测对象,测试规范对象的每个属性值都必须是 predicate 。 每个 predicate 作用于待检测对象对应的属性值,只要有一个 predicate 返回 true,则 whereAny 返回 true,否则返回 false 。

whereAny 非常适合于需要声明式表示约束的函数比如 filter and find

See also propSatisfies, where.
// pred :: Object -> Boolean const pred = R.whereAny({ a: R.equals('foo'), b: R.complement(R.equals('xxx')), x: R.gt(R.__, 10), y: R.lt(R.__, 20) }); pred({a: 'foo', b: 'xxx', x: 8, y: 34}); //=> true pred({a: 'xxx', b: 'xxx', x: 9, y: 21}); //=> false pred({a: 'bar', b: 'xxx', x: 10, y: 20}); //=> false pred({a: 'foo', b: 'bar', x: 10, y: 20}); //=> true pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> true

whereEq Object

{String: *} → {String: *} → Boolean
Parameters
  • spec
  • testObj
Returns Boolean

Added in v0.14.0

接受一个测试规范对象和一个待检测对象,如果测试满足规范,则返回 true,否则返回 false。如果对于每一个测试规范对象的属性值,待检测对象中都有一个对应的相同属性值,则 where 返回 true,否则返回 false 。

whereEqwhere 的一种特殊形式。

See also propEq, where.
// pred :: Object -> Boolean const 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

without List

[a] → [a] → [a]
Parameters
  • list1

    The values to be removed from list2.

  • list2

    The array to remove values from.

Returns Array The new array without values in `list1`.

Added in v0.19.0

求第二个列表中,未包含在第一个列表中的任一元素的集合。通过 R.equals 函数进行相等性判断。

若传入的是 transfomer,则当前函数用作 transducer,对传入的 transformer 进行封装 。

R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4]

xor Logic

a → b → Boolean
Parameters
  • a
  • b
Returns Boolean true if one of the arguments is truthy and the other is falsy

Added in v0.27.1

异或操作。

如果其中一个参数为真,另一个参数为假,则返回true ;否则返回false

See also or, and.
R.xor(true, true); //=> false R.xor(true, false); //=> true R.xor(false, true); //=> true R.xor(false, false); //=> false

xprod List

[a] → [b] → [[a,b]]
Parameters
  • as

    The first list.

  • bs

    The second list.

Returns Array The list made by combining each possible pair from `as` and `bs` into pairs (`[a, b]`).

Added in v0.1.0

将两个列表的元素两两组合,生成一个新的元素对列表。

R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]

zip List

[a] → [b] → [[a,b]]
Parameters
  • list1

    The first array to consider.

  • list2

    The second array to consider.

Returns Array The list made by pairing up same-indexed elements of `list1` and `list2`.

Added in v0.1.0

将两个列表对应位置的元素组合,生成一个新的元素对列表。生成的列表长度取决于较短的输入列表的长度。

注意,zip 等价于 zipWith(function(a, b) { return [a, b] })

R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']]

zipObj List

[String] → [*] → {String: *}
Parameters
  • keys

    The array that will be properties on the output object.

  • values

    The list of values on the output object.

Returns Object The object made by pairing up same-indexed elements of `keys` and `values`.

Added in v0.3.0

将两个列表对应位置的元素作为键值对组合,生成一个新的键值对的列表。生成的列表长度取决于较短的输入列表的长度。

注意,zipObj 等价于 pipe(zip, fromPairs)

R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3}

zipWith List

((a, b) → c) → [a] → [b] → [c]
Parameters
  • fn

    The function used to combine the two elements into one value.

  • list1

    The first array to consider.

  • list2

    The second array to consider.

Returns Array The list made by combining same-indexed elements of `list1` and `list2` using `fn`.

Added in v0.1.0

将两个列表对应位置的元素通过一个函数处理,生成一个新的元素的列表。生成的列表长度取决于较短的输入列表的长度。

const f = (x, y) => { // ... }; R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')]