ArrayRunner.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. "use strict";
  2. var Runner = require('./Runner');
  3. /**
  4. * This class is an array runner used to run a pipeline against a static array of data
  5. * @param {Array} items The array source of the data
  6. **/
  7. var klass = module.exports = function ArrayRunner(array){
  8. base.call(this);
  9. if (!array || array.constructor !== Array ) throw new Error('Array runner requires an array');
  10. this._array = array;
  11. this._position = 0;
  12. this._state = Runner.RunnerState.RUNNER_ADVANCED;
  13. }, base = Runner, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  14. /**
  15. * Get the next result from the array.
  16. *
  17. * @method getNext
  18. * @param [callback] {Function}
  19. */
  20. proto.getNext = function getNext(callback) {
  21. var obj, err;
  22. try {
  23. if (this._state === Runner.RunnerState.RUNNER_ADVANCED) {
  24. if (this._position < this._array.length){
  25. obj = this._array[this._position++];
  26. } else {
  27. this._state = Runner.RunnerState.RUNNER_EOF;
  28. }
  29. }
  30. } catch (ex) {
  31. err = ex;
  32. this._state = Runner.RunnerState.RUNNER_ERROR;
  33. }
  34. return callback(err, obj, this._state);
  35. };
  36. /**
  37. * Save any state required to yield.
  38. *
  39. * @method saveState
  40. */
  41. proto.saveState = function saveState() {
  42. //nothing to do here
  43. };
  44. /**
  45. * Restore saved state, possibly after a yield. Return true if the runner is OK, false if
  46. * it was killed.
  47. *
  48. * @method restoreState
  49. */
  50. proto.restoreState = function restoreState() {
  51. //nothing to do here
  52. };
  53. /**
  54. * Returns a description of the Runner
  55. *
  56. * @method getInfo
  57. * @param [explain]
  58. * @param [planInfo]
  59. */
  60. proto.getInfo = function getInfo(explain) {
  61. if (explain){
  62. return {
  63. type: this.constructor.name,
  64. nDocs: this._array.length,
  65. position: this._position,
  66. state: this._state
  67. };
  68. }
  69. return undefined;
  70. };
  71. /**
  72. * dispose of the Runner.
  73. *
  74. * @method reset
  75. */
  76. proto.reset = function reset(){
  77. this._array = [];
  78. this._position = 0;
  79. this._state = Runner.RunnerState.RUNNER_DEAD;
  80. };