UNPKG

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