javascriptrxjstransducer

Is it possible to implement scan as a transducer


I notice that scan is missing from the various transducer libraries that I looked at (e.g transducers-js). Is it impossible to implement or am I missing something?


Solution

  • Actually I can answer my own question. I was trying to implement it in a functional way and I misunderstood how the transducer interface is used. Looking at the source code from transducers-js, they generally keep state in an object and I can implement scan the same way:

    var Scan = function( agg, start, xf ){
        this.xf = xf;
        this.agg = agg;
        this.accum = start;
    }
    Scan.prototype.init = function(){
        return this.xf.init();
    }
    Scan.prototype.result = function(v) {
        return this.xf.result(v);
    }
    Scan.prototype.step = function( result, input ) {
        this.accum = this.agg( this.accum, input );
        return this.xf.step( result, this.accum );
    }
    
    var scan = function(agg, start) {
        return function (xf) {
            return new Scan(agg, start, xf);
        }
    }