Cursor.js 982 B

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