primitive-iterator.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. var clear = require('es5-ext/array/#/clear')
  3. , assign = require('es5-ext/object/assign')
  4. , setPrototypeOf = require('es5-ext/object/set-prototype-of')
  5. , toStringTagSymbol = require('es6-symbol').toStringTag
  6. , d = require('d')
  7. , autoBind = require('d/auto-bind')
  8. , Iterator = require('es6-iterator')
  9. , kinds = require('./iterator-kinds')
  10. , defineProperties = Object.defineProperties, keys = Object.keys
  11. , unBind = Iterator.prototype._unBind
  12. , PrimitiveMapIterator;
  13. PrimitiveMapIterator = module.exports = function (map, kind) {
  14. if (!(this instanceof PrimitiveMapIterator)) {
  15. return new PrimitiveMapIterator(map, kind);
  16. }
  17. Iterator.call(this, keys(map.__mapKeysData__), map);
  18. if (!kind || !kinds[kind]) kind = 'key+value';
  19. defineProperties(this, {
  20. __kind__: d('', kind),
  21. __keysData__: d('w', map.__mapKeysData__),
  22. __valuesData__: d('w', map.__mapValuesData__)
  23. });
  24. };
  25. if (setPrototypeOf) setPrototypeOf(PrimitiveMapIterator, Iterator);
  26. PrimitiveMapIterator.prototype = Object.create(Iterator.prototype, assign({
  27. constructor: d(PrimitiveMapIterator),
  28. _resolve: d(function (i) {
  29. if (this.__kind__ === 'value') return this.__valuesData__[this.__list__[i]];
  30. if (this.__kind__ === 'key') return this.__keysData__[this.__list__[i]];
  31. return [this.__keysData__[this.__list__[i]],
  32. this.__valuesData__[this.__list__[i]]];
  33. }),
  34. _unBind: d(function () {
  35. this.__keysData__ = null;
  36. this.__valuesData__ = null;
  37. unBind.call(this);
  38. }),
  39. toString: d(function () { return '[object Map Iterator]'; })
  40. }, autoBind({
  41. _onAdd: d(function (key) { this.__list__.push(key); }),
  42. _onDelete: d(function (key) {
  43. var index = this.__list__.lastIndexOf(key);
  44. if (index < this.__nextIndex__) return;
  45. this.__list__.splice(index, 1);
  46. }),
  47. _onClear: d(function () {
  48. clear.call(this.__list__);
  49. this.__nextIndex__ = 0;
  50. })
  51. })));
  52. Object.defineProperty(PrimitiveMapIterator.prototype, toStringTagSymbol,
  53. d('c', 'Map Iterator'));