genIterator.js 922 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var _ = require("./_");
  2. // Hack: we don't create new object to pass the newly iterated object.
  3. var $ArrIterContainer = {};
  4. var ArrIter = _.extendPrototype(function (arr) {
  5. this.arr = arr;
  6. this.len = arr.length;
  7. }, {
  8. i: 0,
  9. next: function () {
  10. var self = this;
  11. $ArrIterContainer.value = self.arr[self.i++];
  12. $ArrIterContainer.done = self.i > self.len;
  13. return $ArrIterContainer;
  14. }
  15. });
  16. /**
  17. * Generate a iterator
  18. * @param {Any} obj
  19. * @return {Function}
  20. */
  21. function genIterator (obj) {
  22. if (obj) {
  23. var gen = obj[_.Promise.Symbol.iterator];
  24. if (_.isFunction(gen)) {
  25. return gen.call(obj);
  26. }
  27. if (obj instanceof Array) {
  28. return new ArrIter(obj);
  29. }
  30. if (_.isFunction(obj.next)) {
  31. return obj;
  32. }
  33. }
  34. throw new TypeError("invalid_argument");
  35. }
  36. module.exports = genIterator;