ArrayRunner.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. * @class ArrayRunner
  6. * @extends mungedb-aggregate.query.Runner
  7. * @namespace mungedb-aggregate.query
  8. * @module mungedb-aggregate
  9. * @constructor
  10. * @param {Array} items The array source of the data
  11. */
  12. var klass = module.exports = function ArrayRunner(array){
  13. base.call(this);
  14. if (!(array instanceof Array)) throw new Error("Array runner requires an array");
  15. this._array = array;
  16. this._position = 0;
  17. this._state = Runner.RunnerState.RUNNER_ADVANCED;
  18. }, base = Runner, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}}); //jshint ignore:line
  19. /**
  20. * Get the next result from the array.
  21. * @method getNext
  22. * @param callback {Function}
  23. */
  24. proto.getNext = function getNext(callback) {
  25. var obj;
  26. if (this._state === Runner.RunnerState.RUNNER_ADVANCED) {
  27. if (this._position < this._array.length){
  28. obj = this._array[this._position++];
  29. } else {
  30. this._state = Runner.RunnerState.RUNNER_EOF;
  31. }
  32. }
  33. return obj;
  34. };
  35. /**
  36. * Save any state required to yield.
  37. * @method saveState
  38. */
  39. proto.saveState = function saveState() {
  40. //nothing to do here
  41. };
  42. /**
  43. * Restore saved state, possibly after a yield. Return true if the runner is OK, false if
  44. * it was killed.
  45. * @method restoreState
  46. */
  47. proto.restoreState = function restoreState() {
  48. //nothing to do here
  49. };
  50. /**
  51. * Returns a description of the Runner
  52. * @method getInfo
  53. * @param [explain]
  54. * @param [planInfo]
  55. */
  56. proto.getInfo = function getInfo(explain) {
  57. if (explain){
  58. return {
  59. type: this.constructor.name,
  60. nDocs: this._array.length,
  61. position: this._position,
  62. state: this._state
  63. };
  64. }
  65. return undefined;
  66. };