Skip to content

Instantly share code, notes, and snippets.

@glifchits
Created September 25, 2017 19:19
Show Gist options
  • Save glifchits/3a4e498597b8fa4b81c3b4f3d50cfab5 to your computer and use it in GitHub Desktop.
Save glifchits/3a4e498597b8fa4b81c3b4f3d50cfab5 to your computer and use it in GitHub Desktop.
map, filter from reduce
function mapper(fn, arr) {
return arr.reduce((acc, i) => [...acc, fn(i)], [])
}
function filterer(pred, arr) {
return arr.reduce((acc, i) => pred(i) ? [...acc, i] : acc, [])
}
console.log(mapper( x => x ** 2, [1, 2, 3] )) // => [1, 4, 9]
console.log(filterer( x => x >= 2, [1, 2, 3] )) // => [2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment