Skip to content

Instantly share code, notes, and snippets.

@santiago-su
Created June 27, 2019 11:47
Show Gist options
  • Save santiago-su/770f2e7a85f9af82d8d466774e29d086 to your computer and use it in GitHub Desktop.
Save santiago-su/770f2e7a85f9af82d8d466774e29d086 to your computer and use it in GitHub Desktop.
// Playing around with currying and composing
const curry = fn => {
const arity = fn.length;
return function _curry(...args) {
if (args.length < arity) {
return _curry.bind(null, ...args);
}
return fn.call(null, ...args);
};
};
const compose = (...fns) => (...args) =>
fns.reduceRight((res, fn) => [fn.call(null, ...res)], args)[0];
// Data example
const data = [{id:1, name: 'a'}, {id:2, name: 'b'}, {id:3, name: 'c'}, {id:4, name: 'd'}, {id:5, name: 'e'}, {id:6, name: 'f'}, {id: 1, name: 'g'}, {id: 1, name: 'a'}];
// Curried filter functions
const filterById = curry((id,xs) => xs.filter(x => x.id === id))
const filterByName = curry((name, xs) => xs.filter(x => x.name === name))
// Partial application
const x1 = fId(1)
const filteredByX1 = x1(data)
const x2 = fNM('g')
const filteredByX2 = x2(data)
// Reducing without composing
const res = data.reduce((acc, curr) => { return x1(acc) }, data)
const res2 = res.reduce((acc, curr) => x2(acc), res) // => [{ id: 1, name: 'g' }]
// Composing
const kk = [x1,x2]
compose(...kk)(data) // => [{ id: 1, name: 'g' }]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment