All files / app/lib prescan.js

100% Statements 48/48
100% Branches 17/17
100% Functions 4/4
100% Lines 48/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 4821x 21x 21x 21x 6x 6x 6x 3x 3x 3x 3x 3x 3x 3x 6x 21x 21x 21x 21x 21x 21x 5x 5x 3x 3x 3x 3x 3x 3x 21x 21x 21x 26x 26x 16x 26x 26x 26x 26x 26x 21x 21x 21x 3x 3x 21x 21x 21x
const Streamz = require('streamz');
const Promise = require('bluebird');
const util = require('util');
 
function Prescan(count,fn) {
  if (!(this instanceof Prescan))
    return new Prescan(count,fn);
 
  Streamz.call(this);
  // Allow a custom collection function as first argument
  this.count = count;
  this.fn = fn;
  this.buffer = [];
  this.i = 0;
}
 
util.inherits(Prescan,Streamz);
 
Prescan.prototype.buffer = undefined;
 
Prescan.prototype._push = function() {
  if (!this.buffer)
    return Promise.resolve();
 
  const buffer = this.buffer;
  this.buffer = undefined;
 
  return Promise.try(() =>this.fn(buffer))
  .then(() => buffer.forEach(d => this.push(d)));
};
 
Prescan.prototype._fn = function(d) {
  if (!this.buffer)
    return d;
 
  this.i +=  d.length || 1;
  this.buffer.push(d);
 
  if (this.i >= this.count)
    return this._push();
};
 
Prescan.prototype._flush = function(cb) {
  this._push()
    .then( () => setImmediate( () => Streamz.prototype._flush(cb)));
};
 
module.exports = Prescan;