From 3d8167e135524daa0d67493532910cd47359b8a6 Mon Sep 17 00:00:00 2001 From: Sergey Zavgorodniy Date: Mon, 19 Dec 2016 18:04:59 +0300 Subject: [PATCH] Fix enumerable array polyfill --- src/utils/polyfill.js | 85 ++++++++++++++++++++++++++++--------------- 1 file changed, 55 insertions(+), 30 deletions(-) diff --git a/src/utils/polyfill.js b/src/utils/polyfill.js index 6cbcafa..62cfc0d 100644 --- a/src/utils/polyfill.js +++ b/src/utils/polyfill.js @@ -1,38 +1,63 @@ -/** - * Array.prototype.find() - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find - */ -(function() { - function polyfill(fnName) { - if (!Array.prototype[fnName]) { - Array.prototype[fnName] = function(predicate /*, thisArg */ ) { - var i, len, test, thisArg = arguments[1]; - - if (typeof predicate !== "function") { - throw new TypeError(); +(function () { + /** + * Array.prototype.find() + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find + */ + if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { + value: function (predicate) { + 'use strict'; + if (this == null) { + throw new TypeError('Array.prototype.find called on null or undefined'); } - - test = !thisArg ? predicate : function() { - return predicate.apply(thisArg, arguments); - }; - - for (i = 0, len = this.length; i < len; i++) { - if (test(this[i], i, this) === true) { - return fnName === "find" ? this[i] : i; - } + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); } + var list = Object(this); + var length = list.length >>> 0; + var thisArg = arguments[1]; + var value; - if (fnName !== "find") { - return -1; + for (var i = 0; i < length; i++) { + value = list[i]; + if (predicate.call(thisArg, value, i, list)) { + return value; + } } - }; - } + return undefined; + } + }); } + /** + * Array.prototype.findIndex() + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex + */ + if (!Array.prototype.findIndex) { + Object.defineProperty(Array.prototype, 'findIndex', { + value: function (predicate) { + 'use strict'; + if (this == null) { + throw new TypeError('Array.prototype.findIndex called on null or undefined'); + } + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + var list = Object(this); + var length = list.length >>> 0; + var thisArg = arguments[1]; + var value; - for (var i in { - find: 1, - findIndex: 1 - }) { - polyfill(i); + for (var i = 0; i < length; i++) { + value = list[i]; + if (predicate.call(thisArg, value, i, list)) { + return i; + } + } + return -1; + }, + enumerable: false, + configurable: false, + writable: false + }); } }());