Installation | | | |
Install the Ramda library | npm install ramda | Ramda installed | |
Import | | | |
Import Ramda into your project | const R = require('ramda'); | Ramda imported | |
List | | | |
Map a function over a list | const double = R.map(x => x * 2, [1, 2, 3, 4]); | [2, 4, 6, 8] | List |
Filter a list using a predicate | const evens = R.filter(x => x % 2 === 0, [1, 2, 3, 4]); | [2, 4] | List |
Reduce a list using a function | const sum = R.reduce((acc, x) => acc + x, 0, [1, 2, 3, 4]); | 10 | List |
Check if a list contains a value | const has3 = R.contains(3, [1, 2, 3, 4]); | true | List |
Pluck values of a property from a list of objects | const ages = R.pluck('age', [{name: 'Alice', age: 30}, {name: 'Bob', age: 25}]); | [30, 25] | List |
Function | | | |
Create a partially applied function | const add = (a, b) => a + b; | | Function |
| const add5 = R.partial(add, [5]); | | Function |
Compose multiple functions | const double = x => x * 2; | | Function |
| const square = x => x * x; | | Function |
| const doubleAndSquare = R.compose(square, double); | | Function |
Relation | | | |
Check if a value is less than another value | const lessThan5 = R.lt(R.__, 5); | true | Relation |
Check if a value is equal to another value | const equals5 = R.equals(5); | true | Relation |
String | | | |
Split a string into an array of strings | const splitBySpace = R.split(' ', 'Hello World'); | ['Hello', 'World'] | String |
Join an array of strings into a single string | const joinWithComma = R.join(', ', ['Hello', 'World']); | 'Hello, World' | String |
Object | | | |
Merge two objects | const merged = R.merge({a: 1, b: 2}, {b: 3, c: 4}); | {a: 1, b: 3, c: 4} | Object |
Get the value of a property from an object | const value = R.prop('a', {a: 1, b: 2}); | 1 | Object |
Set the value of a property on an object | const newObj = R.assoc('c', 3, {a: 1, b: 2}); | {a: 1, b: 2, c: 3} | Object |
Create a new object with only specific properties | const picked = R.pick(['a', 'c'], {a: 1, b: 2, c: 3}); | {a: 1, c: 3} | Object |
Logic | | | |
Create a new function that returns true if both predicates return true | const isEven = x => x % 2 === 0; | | Logic |
| const isGt10 = x => x > 10; | | Logic |
| const isEvenAndGt10 = R.both(isEven, isGt10); | | Logic |
Create a new function that returns true if either predicate returns true | const isOdd = x => x % 2 !== 0; | | Logic |
| const isGt20 = x => x > 20; | | Logic |
| const isOddOrGt20 = R.either(isOdd, isGt20); | | Logic |
Math | | | |
Add two numbers | const added = R.add(5, 3); | 8 | Math |
Subtract two numbers | const subtracted = R.subtract(5, 3); | 2 | Math |
Multiply two numbers | const multiplied = R.multiply(5, 3); | 15 | Math |
Divide two numbers | const divided = R.divide(10, 2); | 5 | Math |