Skip to content

Instantly share code, notes, and snippets.

@aykutyaman
Created February 4, 2020 14:56
Show Gist options
  • Save aykutyaman/a08cbc740c79370ab3090e684a582d40 to your computer and use it in GitHub Desktop.
Save aykutyaman/a08cbc740c79370ab3090e684a582d40 to your computer and use it in GitHub Desktop.
const compose = (...args) => n => args.reverse().reduce((acc, f) => f(acc), n);
var mapReducer = fn => combineFn => (acc, v) => combineFn(acc, fn(v));
var filterReducer = fn => combineFn => (acc, v) => fn(v) ? combineFn(acc, v) : acc;
var add1 = n => n + 1;
var isOdd = n => n % 2 === 1;
var sum = (acc, n) => Number(acc) + n;
var list = [1, 3, 4, 6, 9, 12, 13, 16, 21];
var transducer = compose(mapReducer(add1), filterReducer(isOdd));
list.reduce(transducer(sum), 0); // 42
// --------------- transducers-js -----------------------------
var t = require('transducers-js');
let { map, filter, transduce, into } = t;
let xf = compose(map(add1), filter(isOdd));
transduce(xf, sum, 0, [1, 3, 4, 6, 9, 12, 13, 16, 21]); // 42
into([], xf, [1, 3, 4, 6, 9, 12, 13, 16, 21]); // [5, 7, 13, 17]
into('', xf, [1, 3, 4, 6, 9, 12, 13, 16, 21]); // '571317'
into(0, xf, [1, 3, 4, 6, 9, 12, 13, 16, 21]); // why not 42? Maybe into works differently here?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment