Skip to content

Instantly share code, notes, and snippets.

@SirMoustache
Created June 18, 2019 10:47
Show Gist options
  • Select an option

  • Save SirMoustache/9519523f5cf952d799b9d02ee16da2c1 to your computer and use it in GitHub Desktop.

Select an option

Save SirMoustache/9519523f5cf952d799b9d02ee16da2c1 to your computer and use it in GitHub Desktop.
Transdusers
// Test Array
const testArr = [1, 2, 3, 4, 5, 6];
// Utils
const increment = val => val + 1;
const greaterThan = min => val => val > min;
const compose = (...fns) => (val) => fns.reduceRight((acc, fn) => fn(acc), val);
const optCompose = (...fns) => fns.reduce((acc, fn) => x => acc(fn(x)));
// Base Reducers
const mapReducer = (acc, val) => acc.concat(val);
const filteReducer = (acc, val) => val ? acc.concat(val) : acc;
const anyReducer = (acc, val) => acc ? acc : val;
const allReducer = (acc, val) => acc ? acc : false;
// Reducers makers
const makeMapReducer = fn => (acc, val) => mapReducer(acc, fn(val));
const makeFilterReducer = fn => (acc, val) => filteReducer(acc, fn(val));
const makeAnyReducer = fn => (acc, val) => anyReducer(acc, fn(val))
// Transducers makers
const tMap = transform => reducer => (acc, val) => reducer(acc, transform(val))
const tFilter = predicate => reducer => (acc, val) => predicate(val) ? reducer(acc, val) : acc;
const tAny = transform => reducer => (acc, val) => acc ? acc : reducer(acc, transform(val));
// It's action time
const incrementTransducer = tMap(increment);
const greaterThanTransducer = tFilter(greaterThan(2));
const anyTransducer = tAny(greaterThan(3))
const pipeLine = compose(greaterThanTransducer, incrementTransducer, anyTransducer);
const tranducerInAction = testArr.reduce(pipeLine(anyReducer), false);
console.log('tranducerInAction: ', tranducerInAction); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment