Guest User

Untitled

a guest
Nov 13th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.57 KB | None | 0 0
  1. function foldl(f, acc, [x, ...xs]) {
  2. return typeof x === 'undefined' ? acc : foldl(f, f(acc, x), xs);
  3. }
  4.  
  5. foldl((x, y) => x * y, 1, [2, 3, 4]);
  6. // => 24
  7.  
  8. function map(f, [...xs]) {
  9. return foldl((x, y) => x.concat([f(y)]), [], xs);
  10. }
  11.  
  12. map(x => x * 2, [1, 2, 3, 4]);
  13. // => [ 2, 4, 6, 8 ]
  14.  
  15. function filter(predicate, [...xs]) {
  16. return foldl((x, y) => predicate(y) ? x.concat(y) : x, [], xs);
  17. }
  18.  
  19. filter(x => x % 2 === 0, [1, 2, 3, 4, 5]);
  20. // => [ 2, 4 ]
  21.  
  22. const head = ([x, ..._]) => x;
  23.  
  24. head([1, 2, 3]);
  25. // => 1
  26.  
  27. const tail = ([_, ...xs]) => xs;
  28.  
  29. tail([1, 2, 3]);
  30. // => [ 2, 3 ]
Add Comment
Please, Sign In to add comment