Skip to content

Instantly share code, notes, and snippets.

@xgrommx
Forked from kl0tl/transducers.js
Last active August 29, 2015 14:06
Show Gist options
  • Save xgrommx/336253e315b4ae4d5dcc to your computer and use it in GitHub Desktop.
Save xgrommx/336253e315b4ae4d5dcc to your computer and use it in GitHub Desktop.
var caller = Function.prototype.bind.bind(Function.prototype.call);
var slice = caller(Array.prototype.slice);
var concat = caller(Array.prototype.concat);
function map(transform) {
return function (combine) {
return function (accumulator, value) {
return combine(accumulator, transform(value));
};
};
}
function filter(transform) {
return function (combine) {
return function (accumulator, value) {
return transform(value) ? combine(accumulator, value) : accumulator;
};
};
}
function compose() {
var transducers = slice(arguments);
return function (combine) {
return transducers.reduceRight(function (combine, transducer) {
return transducer(combine);
}, combine);
}
}
function odd(value) { return value % 2 }
function add1(value) { return value + 1 }
[9, 8, 7].reduce(compose(map(add1), filter(odd))(concat), [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment