Skip to content

Instantly share code, notes, and snippets.

@artisin
Last active March 28, 2019 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save artisin/6fd1e9305f6a1ce087df to your computer and use it in GitHub Desktop.
Save artisin/6fd1e9305f6a1ce087df to your computer and use it in GitHub Desktop.

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