Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Reduced {
- constructor(value) {
- this.value = value
- }
- }
- const reduced = x => new Reduced(x)
- const reduce = (reducer, init, arr) => {
- if (arr.length === 0) {
- return init
- }
- if (init instanceof Reduced) {
- return init.value
- }
- const [head, ...tail] = arr
- return reduce(reducer, reducer(init, head), tail)
- }
- const filter = pred => next =>
- (arr, x) =>
- pred(x)
- ? next(arr, x)
- : arr
- const map = f => next =>
- (arr, x) =>
- next(arr, f(x))
- const take = n => next =>
- (arr, x) =>
- arr.length < n
- ? next(arr, x)
- : reduced(arr)
- const compose = (...fns) => a =>
- fns.reduceRight((x, f) => f(x), a)
- const transduce = (xf, identity, init, arr) =>
- reduce(xf(identity), init, arr)
- const append = (arr, x) =>
- arr.concat(x)
- console.log(
- transduce(
- compose(
- filter(x => { console.log("filter", x); return x % 2 === 0 }),
- map(x => { console.log("map", x); return x * 10 }),
- take(2),
- ),
- append,
- [],
- Array.from({ length: 1000 }, (_, i) => i),
- )
- )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement