-
-
Save GrayedFox/524b8a430c0e67d094a121b9e62c3eef to your computer and use it in GitHub Desktop.
| // 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 | |
| } | |
| } | |
| } |
They are nearly the same!
However Array.prototype.indexOf uses strict equality whereas Array.prototype.includes uses the same-value-zero algorithm which behaves differently for NaN. I wanted the polyfill to account for NaN 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 - and indexOf has IE9 and older support which is sort of the point of a polyfill I guess.
Thanks for pointing it out 👍
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
afaik
this.includes(item)is exactly the same asthis.indexOf(item) !== -1. Sothis.indexOf(item) !== -1is obsolete.https://gist.github.com/GrayedFox/524b8a430c0e67d094a121b9e62c3eef#file-arrayremovemethod-js-L8