|
| 1 | +// https://tc39.github.io/ecma262/#sec-array.prototype.find |
| 2 | +if (!Array.prototype.find) { |
| 3 | + Object.defineProperty(Array.prototype, "find", { |
| 4 | + value: function(predicate) { |
| 5 | + // 1. Let O be ? ToObject(this value). |
| 6 | + if (this == null) { |
| 7 | + throw TypeError('"this" is null or not defined'); |
| 8 | + } |
| 9 | + |
| 10 | + var o = Object(this); |
| 11 | + |
| 12 | + // 2. Let len be ? ToLength(? Get(O, "length")). |
| 13 | + var len = o.length >>> 0; |
| 14 | + |
| 15 | + // 3. If IsCallable(predicate) is false, throw a TypeError exception. |
| 16 | + if (typeof predicate !== "function") { |
| 17 | + throw TypeError("predicate must be a function"); |
| 18 | + } |
| 19 | + |
| 20 | + // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. |
| 21 | + var thisArg = arguments[1]; |
| 22 | + |
| 23 | + // 5. Let k be 0. |
| 24 | + var k = 0; |
| 25 | + |
| 26 | + // 6. Repeat, while k < len |
| 27 | + while (k < len) { |
| 28 | + // a. Let Pk be ! ToString(k). |
| 29 | + // b. Let kValue be ? Get(O, Pk). |
| 30 | + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). |
| 31 | + // d. If testResult is true, return kValue. |
| 32 | + var kValue = o[k]; |
| 33 | + if (predicate.call(thisArg, kValue, k, o)) { |
| 34 | + return kValue; |
| 35 | + } |
| 36 | + // e. Increase k by 1. |
| 37 | + k++; |
| 38 | + } |
| 39 | + |
| 40 | + // 7. Return undefined. |
| 41 | + return undefined; |
| 42 | + }, |
| 43 | + configurable: true, |
| 44 | + writable: true |
| 45 | + }); |
| 46 | +} |
0 commit comments