Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function foldl(f, acc, [x, ...xs]) {
- return typeof x === 'undefined' ? acc : foldl(f, f(acc, x), xs);
- }
- foldl((x, y) => x * y, 1, [2, 3, 4]);
- // => 24
- function map(f, [...xs]) {
- return foldl((x, y) => x.concat([f(y)]), [], xs);
- }
- map(x => x * 2, [1, 2, 3, 4]);
- // => [ 2, 4, 6, 8 ]
- function filter(predicate, [...xs]) {
- return foldl((x, y) => predicate(y) ? x.concat(y) : x, [], xs);
- }
- filter(x => x % 2 === 0, [1, 2, 3, 4, 5]);
- // => [ 2, 4 ]
- const head = ([x, ..._]) => x;
- head([1, 2, 3]);
- // => 1
- const tail = ([_, ...xs]) => xs;
- tail([1, 2, 3]);
- // => [ 2, 3 ]
Add Comment
Please, Sign In to add comment