object-iterator.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. var InternalStateModule = require('../internals/internal-state');
  3. var createIteratorConstructor = require('../internals/create-iterator-constructor');
  4. var hasOwn = require('../internals/has-own-property');
  5. var objectKeys = require('../internals/object-keys');
  6. var toObject = require('../internals/to-object');
  7. var OBJECT_ITERATOR = 'Object Iterator';
  8. var setInternalState = InternalStateModule.set;
  9. var getInternalState = InternalStateModule.getterFor(OBJECT_ITERATOR);
  10. module.exports = createIteratorConstructor(function ObjectIterator(source, mode) {
  11. var object = toObject(source);
  12. setInternalState(this, {
  13. type: OBJECT_ITERATOR,
  14. mode: mode,
  15. object: object,
  16. keys: objectKeys(object),
  17. index: 0
  18. });
  19. }, 'Object', function next() {
  20. var state = getInternalState(this);
  21. var keys = state.keys;
  22. while (true) {
  23. if (keys === null || state.index >= keys.length) {
  24. state.object = state.keys = null;
  25. return { value: undefined, done: true };
  26. }
  27. var key = keys[state.index++];
  28. var object = state.object;
  29. if (!hasOwn(object, key)) continue;
  30. switch (state.mode) {
  31. case 'keys': return { value: key, done: false };
  32. case 'values': return { value: object[key], done: false };
  33. } /* entries */ return { value: [key, object[key]], done: false };
  34. }
  35. });