Q6: Implement a polyfill for Array.prototype.some().
Answer
The some() method returns true as soon as at least one existing array element satisfies the callback condition. If no element matches, it returns false.
Array.prototype.mySome = function (callback, thisArg) {
if (this == null) {
throw new TypeError("Array.prototype.mySome called on null or undefined");
}
if (typeof callback !== "function") {
throw new TypeError("Callback must be a function");
}
const array = Object(this);
const length = array.length >>> 0;
for (let i = 0; i < length; i++) {
if (i in array && callback.call(thisArg, array[i], i, array)) {
return true;
}
}
return false;
};
console.log([1, 3, 5, 8].mySome(n => n % 2 === 0));
// true
Explanation
The method short-circuits on the first matching element. It returns false for an empty array because no element satisfies the condition.
Key Takeaways
Some checks whether at least one element matches.
It short-circuits and returns a boolean.