Q9: Implement a polyfill for Array.prototype.includes().
Answer
The includes() method checks whether an array contains a value. It uses SameValueZero equality, meaning NaN matches NaN, and positive and negative zero are treated as equal.
Array.prototype.myIncludes = function (searchElement, fromIndex = 0) {
if (this == null) {
throw new TypeError("Array.prototype.myIncludes called on null or undefined");
}
const array = Object(this);
const length = array.length >>> 0;
if (length === 0) {
return false;
}
let index = Number(fromIndex);
if (Number.isNaN(index)) {
index = 0;
}
index = index < 0 ? Math.ceil(index) : Math.floor(index);
if (index >= length) {
return false;
}
if (index < 0) {
index = Math.max(length + index, 0);
}
for (let i = index; i < length; i++) {
const value = array[i];
if (
value === searchElement ||
(value !== value && searchElement !== searchElement)
) {
return true;
}
}
return false;
};
console.log([1, 2, NaN].myIncludes(NaN));
// true
console.log([1, 2, 3].myIncludes(2, -2));
// true
Explanation
The expression value !== value identifies NaN, because NaN is the only JavaScript value that is not equal to itself. This implementation covers common cases, but exact native compatibility requires careful handling of conversions and array-like lengths.
Key Takeaways
- Includes uses SameValueZero comparison and can find NaN.
- Negative fromIndex values count backward from the array's length.