1

I'm currently learning functional programming and trying to learn a new concept : transducers.

I'm actually getting the point of theory, like it's an advanced map/reduce that aims to provide better time complexity on array / object operations (such as transform / filter / reduce).

Here's my current code, I'm feeling a bit strange about it. I can't tell what's wrong, but it's not a transducer for me (code smell ?)

Can you help me understanding the concept or how to adjust this code snippet to create a "real" transducer ?

const assert = require("assert");
const numbers = [1, 2, 10, 23, 238];

const createFilter = predicate => element => predicate(element);
const createMapper = transform => element => transform(element);
const reducer = (state, element) => state.concat(element);

const isEven = createFilter(i => i % 2 === 0);
const double = createMapper(i => i * 2);

const createTransducer = (map, filter, reducer) => (acc, current) =>
  filter(current) ? reducer(acc, map(current)) : acc;

const transducer = createTransducer(double, isEven, reducer);

/* Testing part */
const expectedResult = [4, 20, 476];
assert.deepEqual(numbers.reduce(transducer, []), expectedResult);
console.log("All test passed :D");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.