Skip to content

Instantly share code, notes, and snippets.

@dydx
Created January 31, 2016 01:02
Show Gist options
  • Save dydx/ffe1b21c5fcd21af8a79 to your computer and use it in GitHub Desktop.
Save dydx/ffe1b21c5fcd21af8a79 to your computer and use it in GitHub Desktop.
console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((x) => x + 1));
console.log([1, 2, 4, 5, 6, 7, 7, 8, 9, 10].filter((x) => x % 2 === 0));
console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.map((x) => x + 1)
.filter((x) => x % 2 === 0));
const mapIncReducer = (result, input) => result.concat(input + 1);
console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].reduce(mapIncReducer, []));
const mapReducer = (f) => (result, input) => result.concat(f(input));
console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].reduce(mapReducer((x) => x + 1), []));
console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].reduce(mapReducer((x) => x - 1), []));
console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].reduce(mapReducer((x) => x * x), []));
const filterEvenReducer = (result, input) => input % 2 === 0 ? result.concat(input) : result;
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce(filterEvenReducer, []));
const filterReducer = (predicate) => (result, input) => predicate(input) ? result.concat(input) : result;
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce(filterReducer((x) => x % 2 === 0), []));
console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.reduce(mapReducer((x) => x + 1), [])
.reduce(filterReducer((x) => x % 2 === 0), []));
console.log([1, 2, 3].concat(4));
console.log(10 + 1);
// result -> input -> result
const mapping = (f) => (reducing) => (result, input) => reducing(result, f(input));
const filtering = (predicate) => (reducing) => (result, input) => predicate(input) ? reducing(result, input) : result;
console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.reduce(mapping((x) => x + 1)((xs, x) => xs.concat(x)), [])
.reduce(filtering((x) => x % 2 === 0)((xs, x) => xs.concat(x)), []));
console.log(mapping((x) => x + 1)((xs, x) => xs.concat(x))([], 1));
console.log(mapping((x) => x + 1)((xs, x) => xs.concat(x))([2], 2));
console.log(mapping((x) => x + 1)((xs, x) => xs.concat(x))([2, 3], 3));
console.log(filtering((x) => x % 2 === 0)((xs, x) => xs.concat(x))([2, 4], 5));
console.log(filtering((x) => x % 2 === 0)((xs, x) => xs.concat(x))([2, 4], 6));
console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.reduce(mapping((x) => x + 1)(filtering((x) => x % 2 === 0)((xs, x) => xs.concat(x))),
[]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment