Skip to content
This repository has been archived by the owner on Dec 4, 2019. It is now read-only.

Fix enumerable array polyfill #260

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 55 additions & 30 deletions src/utils/polyfill.js
Original file line number Diff line number Diff line change
@@ -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
});
}
}());