Skip to content

Instantly share code, notes, and snippets.

@adleroliveira
Last active August 21, 2017 18:34
Show Gist options
  • Save adleroliveira/793a4589db632e446a902244009c7c0e to your computer and use it in GitHub Desktop.
Save adleroliveira/793a4589db632e446a902244009c7c0e to your computer and use it in GitHub Desktop.
transducer from scratch in JS, just to learn and understand how it works.
// Function Composition
const identity = x => x
const compose = (f, g) => x => f(g(x))
const composer = fnArr => fnArr.reduce(compose, identity)
// Map implemented in terms of reduce
const mmap = fn => reducer => (acc, val) => reducer(acc, fn(val))
// Filter implemented in terms of reduce
const mfilter = fn => reducer => (acc, val) => fn(val) ? reducer(acc, val) : acc
// Transducer Helper Function
const transduce = (fns, reducer, init) => data => data.reduce(composer(fns)(reducer), init)
// Reducers
const concat = (a, b) => a.concat([b])
const sum = (a, b) => a + b
const fns = [
mmap(x => x + 1),
mmap(x => x * 3),
mfilter(x => x < 20),
mfilter(x => x % 2 == 0)
]
// Data
const data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const t = transduce(fns, concat, [])
const t2 = transduce(fns, sum, 0)
console.log(t(data))
console.log(t2(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment