Last active
January 9, 2023 11:58
-
-
Save GrayedFox/524b8a430c0e67d094a121b9e62c3eef to your computer and use it in GitHub Desktop.
Array.remove safe polyfill
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
// remove the first instance of an item inside an array (extends native array object) | |
if (!Array.prototype.remove) { | |
Array.prototype.remove = function remove (item) { // eslint-disable-line no-extend-native | |
if (!(this || Array.isArray(this))) { | |
throw new TypeError() | |
} | |
if (this.indexOf(item) !== -1) { | |
this.splice(this.indexOf(item), 1) | |
return this | |
} | |
// handles cases where item is a finite index and element at given index is defined | |
if (typeof this[item] !== 'undefined' && item >= 0 && Number.isFinite(item)) { | |
this.splice(item, 1) | |
return this | |
} | |
} | |
} |
Happy new year,
(…happy reading-all-the-forgotton-github-notifications-from-last-year LOL)
Thanks for enlightening me. There is always something new to learn about JavaScript - even after decades :D
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
They are nearly the same!
However
Array.prototype.indexOf
uses strict equality whereasArray.prototype.includes
uses the same-value-zero algorithm which behaves differently forNaN
. I wanted the polyfill to account forNaN
and return true in this instance - but as that's the only difference I can indeed remove the includes check - so not quite exactly the same but in this case superfluous as comparisons of all other types return the same result - andindexOf
has IE9 and older support which is sort of the point of a polyfill I guess.Thanks for pointing it out 👍