Skip to content

Instantly share code, notes, and snippets.

@addityasingh
Last active January 15, 2017 23:24
Show Gist options
  • Save addityasingh/b624e8ce732f88eb41c1f16df7d24562 to your computer and use it in GitHub Desktop.
Save addityasingh/b624e8ce732f88eb41c1f16df7d24562 to your computer and use it in GitHub Desktop.
Equivalent pure functions for Functional programming utility functions like .map(), .filter() in ES2015
/**
* A pure function to find key from object, matching a predicate
* similar to https://lodash.com/docs/4.17.4#findKey or Array.findIndex()
* @param {Object} obj: The object to find the specified key from
* @param {Function} fn: The predicate function
*/
const findKey = (obj, fn) => Object.keys(obj).find(k => fn(obj[k]));
//Test code
const data = { a: 1, b: 2, c: 3 };
console.log(findKey(data, (x) => x > 2));
/**
* A pure function to find length of a list
* @param {Array} [first, ...rest]: The list to find the length of
*/
const len = ([first, ...rest]) =>
!first ? 0 : (1 + len(rest));
// Test code
console.log(len([1,2,3,4,5]));
/**
* A pure function to map a list
* @param {Array} [first, ...rest]: The list to map
* @param {Function} fn: The function to apply to the list
*/
const map = ([first, ...rest], fn) =>
!first ? [] : [fn(first), ...map(rest, fn)];
// Test code
console.log(map([1,2,3,4,5], Math.sqrt));
/**
* A pure function to pick specific keys from object, similar to https://lodash.com/docs/4.17.4#omit
* @param {Object}obj: The object to pick the specified keys from
* @param {Array}keys: A list of all keys to omit from obj
*/
const omit = (obj, keys) =>
Object.keys(obj)
.filter(i => !keys.includes(i))
.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {})
console.log(omit(data, ['a', 'c']));
/**
* A pure function to pick specific keys from object, similar to https://lodash.com/docs/4.17.4#pick
* @param {Object}obj: The object to pick the specified keys from
* @param {Array}keys: A list of all keys to pick from obj
*/
const pick = (obj, keys) =>
Object.keys(obj)
.filter(i => keys.includes(i))
.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {})
// Test code
const data = { a: 1, b: 2, c: 3 };
console.log(pick(data, ['a', 'c']));
/**
* A pure function to generate a range of numbers
* @param {Number} start: The start of the range, including this value
* @param {Number} end: The end of the range, excluding this value
*/
const range = (start, end) => Array.from({length: (end - start)}, (v, k) => k + start);
//Test code
console.log(range(1, 10));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment