How to use ramda

Comprehensive ramda code examples:

How to use ramda.modify:

7
8
9
10
11
12
13
14
15
16
17
18


const runCommand = (state, [command, ...output]) => {
  if (command.startsWith('cd ')) {
    const dir = command.slice(3)


    return R.modify(
      'cwd',
      dir === '/'
        ? R.always([])
        : dir === '..'

How to use ramda.applyTo:

977
978
979
980
981
982
983
984
985
* @param {*} x The value
* @param {Function} f The function to apply
* @return {*} The result of applying `f` to `x`
* @example
*
*      const t42 = R.applyTo(42);
*      t42(R.identity); //=> 42
*      t42(R.add(1)); //=> 43
*/

How to use ramda.mergeDeepWith:

9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
* @param {Object} rObj
* @return {Object}
* @see R.mergeWith, R.mergeDeepWithKey
* @example
*
*      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] }}
*/

How to use ramda.paths:

11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
 * @return {Array} A list consisting of values at paths specified by "pathsArray".
 * @see R.path
 * @example
 *
 *      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]
 */




var paths =

How to use ramda.reduced:

12243
12244
12245
12246
12247
12248
12249
12250
12251
* @return {*} The wrapped value.
* @see R.reduce, R.reduceWhile, R.transduce
* @example
*
*     R.reduce(
*       (acc, item) => item > 3 ? R.reduced(acc) : acc.concat(item),
*       [],
*       [1, 2, 3, 4, 5]) // [1, 2, 3]
*/

How to use ramda.constructN:

148
149
150
151
152
153
154
155
156
157
  })
})

context('using Ramda', () => {
  const searchToPlain_R = R.pipe(
    R.constructN(1, URLSearchParams), // string , note that tis isn't interchangeable with R.construct(URLSearchParams)
    R.invoker(0, 'entries'), // Iterable<[string, string]>
    Array.from, // Array<[string, string]>
    _.fromPairs, //  { [key: string]: string }
  )

How to use ramda.move:

10145
10146
10147
10148
10149
10150
10151
10152
10153
* @param {Number} to The destination index
* @param {Array} list The list which will serve to realise the move
* @return {Array} The new list reordered
* @example
*
*      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
*/

How to use ramda.construct:

1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
*      };
*      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 (){...}};
*

How to use ramda.thunkify:

13507
13508
13509
13510
13511
13512
13513
13514
13515
* @return {Function} Expects arguments for `fn` and returns a new function
*  that, when called, applies those arguments to `fn`.
* @see R.partial, R.partialRight
* @example
*
*      R.thunkify(R.identity)(42)(); //=> 42
*      R.thunkify((a, b) => a + b)(25, 17)(); //=> 42
*/

How to use ramda.pipeWith:

185
186
187
188
189
190
191
192
193
194
 * @typedef {Object.<string, any>} Entity
 * @param  {...(Entity[] => Promise<Entity[]>)} pipes
 * @returns high level pipe
 */
compose = (...pipes) => async (input) => {
    return R.pipeWith(R.andThen, pipes)(input)
}

/**
 * Deduplicates entities by specified property

How to use ramda.otherwise:

3
4
5
6
7
8
9
10
11
12
const useDefault = () => ({ firstName: 'Bob', lastName: 'Loblaw' });


//recoverFromFailure :: String -> Promise ({ firstName, lastName })
const recoverFromFailure = R.pipe(
    failedFetch,  // solve -> to andThen
    R.otherwise(useDefault),
    R.andThen(R.pick(['firstName', 'lastName'])),
);
recoverFromFailure(12345).then(console.log);

How to use ramda.mergeDeepWithKey:

How to use ramda.then:

10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
* @sig (e -> b) -> (Promise e a) -> (Promise e b)
* @sig (e -> (Promise f b)) -> (Promise e a) -> (Promise f b)
* @param {Function} onFailure The function to apply. Can return a value or a promise of a value.
* @param {Promise} p
* @return {Promise} The result of calling `p.then(null, onFailure)`
* @see R.then
* @example
*
*      var failedFetch = (id) => Promise.reject('bad ID');
*      var useDefault = () => ({ firstName: 'Bob', lastName: 'Loblaw' })

How to use ramda.composeWith:

1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
* @param {...Function} ...functions The functions to compose
* @return {Function}
* @see R.compose, R.pipeWith
* @example
*
*      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
*

How to use ramda.mapIndexed:

31
32
33
34
35
36
37
38
39
40
// View
const view = R.curry((action$, model) =>
  h('div.list', [
    h('button', {on: {click: [action$, Action.Reverse()]}}, 'Reverse'),
    h('button', {on: {click: [action$, Action.Add()]}}, 'Add'),
    h('ul', R.mapIndexed((item, idx) =>
      h('li', [Component.view(forwardTo(action$, Action.Modify(idx)), item)]), model.items))
  ]))

return {init, Action, update, view}

How to use ramda.xor:

15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
* @param {Any} b
* @return {Boolean} true if one of the arguments is truthy and the other is falsy
* @see R.or, R.and
* @example
*
*      R.xor(true, true); //=> false
*      R.xor(true, false); //=> true
*      R.xor(false, true); //=> true
*      R.xor(false, false); //=> false
*/

How to use ramda.o:

10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
* @return {Function}
* @see R.compose, R.pipe
* @example
*
*      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
*

How to use ramda.andThen:

61
62
63
64
65
66
67
68
69
70
71
  });


const lintReportAndExit = R.pipe(
  R.map(lintComponent),
  (p) => Promise.all(p),
  R.andThen(
    R.pipe(
      R.map(logReport),
      R.reject(R.equals(false)),
      R.unless(R.isEmpty, () => process.exit(1)),

How to use ramda.innerJoin:

210
211
212
213
214
215
216
217
218
219
 * @returns {*}
 */
/* eslint-disable  no-underscore-dangle */
export function getCanChooseAbox(ABOXES = [], allCharts = [], selected = []) {
  return R.compose(
    R.innerJoin((a, b) => a.componentName == b.component_id, R.__, allCharts),
    R.filter(x => selected.indexOf(x.ChartId) < 0)
  )(ABOXES);
}

How to use ramda.hasPath:

4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
* @param {Object} obj The object to check the path in.
* @return {Boolean} Whether the path exists.
* @see R.has
* @example
*
*      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
*/

How to use ramda.splitWhenever:

78
79
80
81
82
83
84
85
86
87
88
89
    R.range(0,R.length(monkeys))
  ))


const monkeys1 = R.compose(
  R.map(parseMonkey(true)),
  R.splitWhenever(R.isEmpty)
)(content)


const monkeys2 = R.compose(
  R.map(parseMonkey(false)),

How to use ramda.startsWith:

334
335
336
337
338
339
340
341
342
343
344
345


/**
 * 检查列表/字符串是否以给定的值开头。
 */
function startsWith$1 (char, val) {
  return R.startsWith(char, val)
}


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

How to use ramda.endsWith:

342
343
344
345
346
347
348
349
350
351
352
/**
 * 检查列表是否以指定的子列表结尾。
 * 同样的,检查字符串是否以指定的子字符串结尾。
 */
function endsWith$1 (char, val) {
  return R.endsWith(char, val)
}


/**
 * 转换成驼峰命名

How to use ramda.forEachObjIndexed:

21
22
23
24
25
26
27
28
29
30
selectedObject = prop(selectedOjectKey, objects);
const { rotateAngle } = selectedObject;
if (rotateAngle != 0) {
  return lines;
}
forEachObjIndexed(obj => {
  //left right line
  if (typeof obj.selected === "undefined" && obj.rotateAngle == 0) {
    lines.push({
      x: obj.left,

How to use ramda.mergeRight:

32
33
34
35
36
37
38
39
40
41
42
        }
        else
            return newPkg
    }
    else
        return R.mergeRight({ tags: ["uncat/new"] }, package)
}


const octokit = new Octokit({
    auth: process.env.GITHUB_TOKEN,

How to use ramda.mergeLeft:

265
266
267
268
269
270
271
272
273
274
  firstName: 'Johnny',
  lastName: 'Doe',
  city: 'Toronto'
};

const { uuid, label, ...data } = mergeLeft(body, originalData);

const updatedAt = new Date();

const userAgent = headers['user-agent'];

How to use ramda.descend:

397
398
399
400
401
402
403
404
405
406
  name: 'clara',
  age: 40
}
var people = [clara, bob, alice];
var ageNameSort = R.sortWith([
  R.descend(R.prop('age')),
  R.ascend(R.prop('name'))
])
log(ageNameSort(people));

How to use ramda.memoize:

8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
* @param {Function} fn The function to memoize.
* @return {Function} Memoized version of `fn`.
* @example
*
*      var count = 0;
*      var factorial = R.memoize(n => {
*        count += 1;
*        return R.product(R.range(1, n + 1));
*      });
*      factorial(5); //=> 120

How to use ramda.ascend:

398
399
400
401
402
403
404
405
406
407
408
  age: 40
}
var people = [clara, bob, alice];
var ageNameSort = R.sortWith([
  R.descend(R.prop('age')),
  R.ascend(R.prop('name'))
])
log(ageNameSort(people));


var list4 = [1, 2, 3, 4, 5];

How to use ramda.memoizeWith:

86
87
88
89
90
91
92
93
94
95
96
 *    @param  {function} fn original function
 *    @return {function} combined Meoized version of fn.
 */


let count = 0;   //=> count to keep track of number of full execution of factorial function
const factorial = R.memoizeWith(Number, n => {
  count += 1;
  return R.product(R.range(1, n + 1));
});

ramda functions:

Sorted by popularity