Last active
October 31, 2015 12:43
-
-
Save razorthink-com/452d9bcc3235cb99edf9 to your computer and use it in GitHub Desktop.
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
const map = (xs, fn) => { | |
const _map = ([x, ...xs], fn, result) => ( | |
x === undefined | |
? result | |
: _map(xs, fn, [...result, fn(x)]) | |
) | |
return _map(xs, fn, []); | |
} | |
const filter = (xs, fn) => { | |
const _filter = ([x, ...xs], fn, result) => ( | |
x === undefined | |
? result | |
: _filter(xs, fn, fn(x) ? [...result, x] : result) | |
) | |
return _filter(xs, fn, []); | |
} | |
const reduce = (xs, fn, initial) => { | |
const _reduce = ([x, ...xs], fn, accumulator) => ( | |
x === undefined | |
? accumulator | |
: _reduce(xs, fn, fn(accumulator, x)) | |
) | |
return _reduce(xs, fn, initial); | |
} | |
// Tests | |
console.log("map", map([1,2,3,4,5,6], n => n * n)) | |
console.log("filter", filter([1,2,3,4,5,6], n => n % 2 == 0)) | |
console.log("reduce", reduce([1,2,3,4,5,6], (sum, n) => sum + n, 0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment