wmakeev
3/26/2015 - 9:01 AM

Transducers (snippets)

Transducers (snippets)


transduce = function(xf, f, init, coll) {
    f = typeof f == "function" ? wrap(f) : f;
    xf = xf(f);
    return reduce(xf, init, coll);
};
var Reduced = function(value) {
    this.__transducers_reduced__ = true;
    this.value = value;
};

var isReduced = function(x) {
    return (x instanceof Reduced) || (x && x.__transducers_reduced__);
};

var deref = function(x) {
    return x.value;
};

var reduce = function(xf, init, coll) {
    xf = typeof xf == "function" ? wrap(xf) : xf;
    var array = coll; // array reduce
    var acc = init;
    for(var i = 0; i < array.length; i++) {
        acc = xf.step(acc, array[i]);
        if(isReduced(acc)) {
            acc = deref(acc);
            break;
        }
    }
    return xf.result(acc);
};
var Map = function(f, xf) {
    this.f = f;
    this.xf = xf;
};
Map.prototype.init = function() {
    return this.xf.init();
};
Map.prototype.result = function(result) {
    return this.xf.result(result);
};
Map.prototype.step = function(result, input) {
    return this.xf.step(result, this.f(input));
};

var map = function(f) {
    return function(xf) {
      return new Map(f, xf);
    };
};