Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Ramda Examples

Ramda Sometime Known As
all every
always const, constant
any some
head first, car
reduce foldl
reduceRight foldr
merge extend, assign, mixin
zipObj object, zipObject

Lift

const madd3 = R.lift(R.curry(function (a, b, c) {
  // [1, 1, 1]
  // [1, 2, 1]
  // [1, 3, 1]
  // [2, 1, 1]
  // [2, 2, 1]
  // [2, 3, 1]
  // [3, 1, 1]
  // [3, 2, 1]
  // [3, 3, 1]
  console.log(arguments);
  return a + b + c;
}));

madd3([1, 2, 3], [1, 2, 3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]

composeK

R.composeK(h, g, f) == R.compose(R.chain(h), R.chain(g), R.chain(f))

//  parseJson :: String -> Maybe *
const parseJson = function (str) {
  try {
    str = JSON.parse(str);
  } catch (e) {
    // error
    return Maybe.Nothing();
  }
  return Maybe.of(str);
};

//  get :: String -> Object -> Maybe *
const get = function (str) {
  return R.compose(Maybe.of, R.prop(str));
};

//  getStateCode :: Maybe String -> Maybe String
var getStateCode = R.composeK(
  R.compose(Maybe.of, R.toUpper),
  get('state'),
  get('address'),
  get('user'),
  parseJson
);

getStateCode(Maybe.of('{"user":{"address":{"state":"ny"}}}')); // Just('NY')
getStateCode(Maybe.of('[Invalid JSON]')); // Nothing()

List Comprehension

/* 
 * Example:
 * Find any integer x, y, z that match the following conditions
 *   1. 0 < x < y < z < 10
 *   2. x * x + y * y = z * z
 * In Python:
 *  [(x,y,z) for x in range(1,10) for y in range(1,10) for z in range(1,10) if x < y and y < z and x * x + y * y == z * z]
 *  >>> [(3, 4, 5)]
 * In Javascript with Ramda:
 */ 
var R = require('ramda');
R.pipe(
  R.sequence(R.of), 
  R.filter(R.apply(function(x, y, z) { 
    return x < y && y < z && (x * x + y * y == z * z); 
  }))
)([R.range(1, 10), R.range(1, 10), R.range(1, 10)])
// [[3, 4, 5]]

Chain

const chain = R.curry(function (a, x) {
  let length = a.length;
  while (length > 0) x = a[--length](x);
  return x;
});
let foo = chain([map(inc), filter(odd), take(5)]);
foo([1,2,3,4,5,6,7,8,9,10]); // [2,4,6]
//or
chain([map(inc), filter(odd), take(5)], [1,2,3,4,5,6,7,8,9,10]); // [2,4,6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment