Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. class Reduced {
  2. constructor(value) {
  3. this.value = value
  4. }
  5. }
  6.  
  7. const reduced = x => new Reduced(x)
  8.  
  9. const reduce = (reducer, init, arr) => {
  10. if (arr.length === 0) {
  11. return init
  12. }
  13.  
  14. if (init instanceof Reduced) {
  15. return init.value
  16. }
  17.  
  18. const [head, ...tail] = arr
  19.  
  20. return reduce(reducer, reducer(init, head), tail)
  21. }
  22.  
  23. const filter = pred => next =>
  24. (arr, x) =>
  25. pred(x)
  26. ? next(arr, x)
  27. : arr
  28.  
  29. const map = f => next =>
  30. (arr, x) =>
  31. next(arr, f(x))
  32.  
  33. const take = n => next =>
  34. (arr, x) =>
  35. arr.length < n
  36. ? next(arr, x)
  37. : reduced(arr)
  38.  
  39. const compose = (...fns) => a =>
  40. fns.reduceRight((x, f) => f(x), a)
  41.  
  42. const transduce = (xf, identity, init, arr) =>
  43. reduce(xf(identity), init, arr)
  44.  
  45. const append = (arr, x) =>
  46. arr.concat(x)
  47.  
  48. console.log(
  49. transduce(
  50. compose(
  51. filter(x => { console.log("filter", x); return x % 2 === 0 }),
  52. map(x => { console.log("map", x); return x * 10 }),
  53. take(2),
  54. ),
  55. append,
  56. [],
  57. Array.from({ length: 1000 }, (_, i) => i),
  58. )
  59. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement