array-iteration.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var bind = require('../internals/function-bind-context');
  2. var IndexedObject = require('../internals/indexed-object');
  3. var toObject = require('../internals/to-object');
  4. var toLength = require('../internals/to-length');
  5. var arraySpeciesCreate = require('../internals/array-species-create');
  6. var push = [].push;
  7. // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation
  8. var createMethod = function (TYPE) {
  9. var IS_MAP = TYPE == 1;
  10. var IS_FILTER = TYPE == 2;
  11. var IS_SOME = TYPE == 3;
  12. var IS_EVERY = TYPE == 4;
  13. var IS_FIND_INDEX = TYPE == 6;
  14. var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
  15. return function ($this, callbackfn, that, specificCreate) {
  16. var O = toObject($this);
  17. var self = IndexedObject(O);
  18. var boundFunction = bind(callbackfn, that, 3);
  19. var length = toLength(self.length);
  20. var index = 0;
  21. var create = specificCreate || arraySpeciesCreate;
  22. var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
  23. var value, result;
  24. for (;length > index; index++) if (NO_HOLES || index in self) {
  25. value = self[index];
  26. result = boundFunction(value, index, O);
  27. if (TYPE) {
  28. if (IS_MAP) target[index] = result; // map
  29. else if (result) switch (TYPE) {
  30. case 3: return true; // some
  31. case 5: return value; // find
  32. case 6: return index; // findIndex
  33. case 2: push.call(target, value); // filter
  34. } else if (IS_EVERY) return false; // every
  35. }
  36. }
  37. return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
  38. };
  39. };
  40. module.exports = {
  41. // `Array.prototype.forEach` method
  42. // https://tc39.github.io/ecma262/#sec-array.prototype.foreach
  43. forEach: createMethod(0),
  44. // `Array.prototype.map` method
  45. // https://tc39.github.io/ecma262/#sec-array.prototype.map
  46. map: createMethod(1),
  47. // `Array.prototype.filter` method
  48. // https://tc39.github.io/ecma262/#sec-array.prototype.filter
  49. filter: createMethod(2),
  50. // `Array.prototype.some` method
  51. // https://tc39.github.io/ecma262/#sec-array.prototype.some
  52. some: createMethod(3),
  53. // `Array.prototype.every` method
  54. // https://tc39.github.io/ecma262/#sec-array.prototype.every
  55. every: createMethod(4),
  56. // `Array.prototype.find` method
  57. // https://tc39.github.io/ecma262/#sec-array.prototype.find
  58. find: createMethod(5),
  59. // `Array.prototype.findIndex` method
  60. // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
  61. findIndex: createMethod(6)
  62. };