Created
November 28, 2016 08:15
-
-
Save subnomo/2ffb6711b32c1a3a2ffa7e22dfce2958 to your computer and use it in GitHub Desktop.
Array.prototype.includes polyfill for TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
declare global { | |
interface Array<T> { | |
includes(searchElement: T): boolean; | |
} | |
} | |
if (!Array.prototype.includes) { | |
Array.prototype.includes = (searchElement: any, ...args: number[]) => { | |
if (this == null) { | |
throw new TypeError("Array.prototype.includes called on null or undefined"); | |
} | |
let O = Object(this); | |
let len = parseInt(O.length, 10) || 0; | |
if (len === 0) { | |
return false; | |
} | |
let n = args[1] || 0; | |
let k: any; | |
if (n >= 0) { | |
k = n; | |
} else { | |
k = len + n; | |
if (k < 0) { | |
k = 0; | |
} | |
} | |
let currentElement: any; | |
while (k < len) { | |
currentElement = O[k]; | |
if (searchElement === currentElement || | |
(searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN | |
return true; | |
} | |
k++; | |
} | |
return false; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Handy! Thank you