Skip to content

Instantly share code, notes, and snippets.

@hch12907
Created June 11, 2017 08:10
Show Gist options
  • Save hch12907/47678df4460f207d38f3f3c13686a612 to your computer and use it in GitHub Desktop.
Save hch12907/47678df4460f207d38f3f3c13686a612 to your computer and use it in GitHub Desktop.
recursive implementation of map and reduce using only lambdas and Array.prototype.pop()
let map = (func, arr) =>
arr.length == 0 ?
[] : ((x, y) => [...y, x])(func(arr.pop()), map(func, arr))
// if you want to pull an one-liner:
// let map = (func, arr) => arr.length == 0 ? [] : ((x, y) => [...y, x])(func(arr.pop()), map(func, arr))
let reduce = (func, initial_value, arr) =>
arr.length == 0 ?
initial_value : ((x, y) => func(y, x))(arr.pop(), reduce(func, initial_value, arr))
// similarly, one-liner:
// let reduce = (func, initial_value, arr) => arr.length == 0 ? initial_value : ((x, y) => func(y, x))(arr.pop(), reduce(func, initial_value, arr))
// Usage of map:
let a = [1, 2, 3]
let b = map(x => x * x, a)
console.log(b) // [1, 4, 9]
// Usage of reduce:
let aa = [1, 2, 3]
let bb = reduce((x, y) => x + y, 0, aa)
console.log(bb) // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment