iterator.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = iterator;
  6. var _isArrayLike = require('lodash/isArrayLike');
  7. var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
  8. var _getIterator = require('./getIterator');
  9. var _getIterator2 = _interopRequireDefault(_getIterator);
  10. var _keys = require('lodash/keys');
  11. var _keys2 = _interopRequireDefault(_keys);
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. function createArrayIterator(coll) {
  14. var i = -1;
  15. var len = coll.length;
  16. return function next() {
  17. return ++i < len ? { value: coll[i], key: i } : null;
  18. };
  19. }
  20. function createES2015Iterator(iterator) {
  21. var i = -1;
  22. return function next() {
  23. var item = iterator.next();
  24. if (item.done) return null;
  25. i++;
  26. return { value: item.value, key: i };
  27. };
  28. }
  29. function createObjectIterator(obj) {
  30. var okeys = (0, _keys2.default)(obj);
  31. var i = -1;
  32. var len = okeys.length;
  33. return function next() {
  34. var key = okeys[++i];
  35. return i < len ? { value: obj[key], key: key } : null;
  36. };
  37. }
  38. function iterator(coll) {
  39. if ((0, _isArrayLike2.default)(coll)) {
  40. return createArrayIterator(coll);
  41. }
  42. var iterator = (0, _getIterator2.default)(coll);
  43. return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
  44. }
  45. module.exports = exports['default'];