Created
June 11, 2017 08:10
-
-
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()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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