Skip to content

Instantly share code, notes, and snippets.

@theptrk
Created April 15, 2017 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theptrk/0000659d7dfa6197c651e2ecee88e08d to your computer and use it in GitHub Desktop.
Save theptrk/0000659d7dfa6197c651e2ecee88e08d to your computer and use it in GitHub Desktop.
// Part 1
// write an array mapping function that can be passed into reduce
const mapping = (transform) => (acc, val) => acc.concat([transform(val)]);
// write an array filtering function that can be passed into reduce
const filtering = (predicate) => (acc, val) => predicate ? acc.concat([val]): acc;
// Part 2
// abstract out the "reduce" logic
const concat = (acc, val) => acc.concat([val]);
const mapping2 = (transform) => (reducer) => (acc, val) => reducer(acc, transform(val));
const filtering2 = (predicate) => (reducer) => (acc, val) => predicate(val) ? reducer(acc, val): acc;
// [1,3,2].reduce(mapping2((x) => x+100)(concat), [])
// -> [101, 103, 102]
// [1,3,2].reduce(filtering2((x)=>x <= 2)(concat), [])
// -> [1, 2]
// Part 3
const reduceArray = (list, folder) => list.reduce(folder(concat), []);
// reduceArray([1,3,2], mapping2((x) => x + 100)
// -> [101, 103, 102]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment