Cursor.js 965 B

123456789101112131415161718192021222324252627282930313233
  1. "use strict";
  2. var Cursor = module.exports = (function(){
  3. // CONSTRUCTOR
  4. /**
  5. * This class is a simplified implementation of the cursors used in MongoDB for reading from an Array of documents.
  6. * @param {Array} items The array source of the data
  7. **/
  8. var klass = function Cursor(items){
  9. var self = this;
  10. if (!(items instanceof Array)) throw new Error("arg `items` must be an Array");
  11. this.cachedData = items.slice(0); // keep a copy
  12. }, base = Object, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  13. proto.ok = function ok(){
  14. return this.cachedData.length > 0 || this.hasOwnProperty("curr");
  15. };
  16. proto.advance = function advance(){
  17. if (this.cachedData.length === 0){
  18. delete this.curr;
  19. return false;
  20. }
  21. this.curr = this.cachedData.shift();
  22. return this.curr;
  23. };
  24. proto.current = function current(){
  25. if (!this.hasOwnProperty("curr")) this.advance();
  26. return this.curr;
  27. };
  28. return klass;
  29. })();