Skip to content

Instantly share code, notes, and snippets.

@harbirchahal
Last active November 19, 2019 08:39
Show Gist options
  • Save harbirchahal/d2f6fe4677d0f864be8df8f24a179ba8 to your computer and use it in GitHub Desktop.
Save harbirchahal/d2f6fe4677d0f864be8df8f24a179ba8 to your computer and use it in GitHub Desktop.
Simplest implementation of array utility functions.
const map = ([head, ...tail], fn) =>
typeof head === 'undefined' ?
[] :
[fn(head), ...map(tail, fn)];
const reduce = ([head, ...tail], fn, value) =>
typeof head === 'undefined' ?
value :
reduce(tail, fn, fn(value, head));
const filter = ([head, ...tail], fn) =>
typeof head === 'undefined' ?
[] :
fn(head) ?
[head, ...filter(tail, fn)] :
filter(tail, fn);
const sequence = (fn1, ...fRest) => (...args) =>
fRest.reduce((arg, fn) => fn(arg), fn1(...args));
const partial = (fn, ...argsLead) => (...argsTrail) =>
fn(...argsLead, ...argsTrail);
const curry = (fn) => curryN(fn, []);
const curryN = (fn, args) =>
args.length === fn.length /* Arity*/ ?
fn(...args) :
(arg) => curryN(fn, [...args, arg]);
const memoize = (fn) => {
const memo = new Map();
return (arg) => memo.has(arg) ?
memo.get(arg) :
memo.set(arg, fn(arg)).get(arg);
};
const lazyMap = (array, mapFn) => ({
get: (index) => mapFn(array[index]),
take: (n) => array.slice(0, n).map(mapFn),
value: () => array.map(mapFn)
});
const lazyMemoMap = (array, mapFn) => {
const memo = [];
return {
get: (index) => {
if (!memo[index]) {
memo[index] = mapFn(array[index]);
}
return memo[index];
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment