The some() method tests whether at least one element in the array passes the test implemented by the provided function.
β Implementation
Array.prototype.customSome = function (callback, thisArg) { if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } for (let i = 0; i < this.length; i++) { if (callback.call(thisArg, this[i], i, this)) { return true; // Return true immediately if a match is found } } return false; // Return false if no element satisfies the condition }; // Example usage: const array = [1, 2, 3, 4, 5]; const even = (element) => element % 2 === 0; console.log(array.customSome(even)); // Output: true console.log(array.customSome((num) => num > 10)); // Output: false
How This Works
- Checks if
callbackis a function- If not, it throws a
TypeError(same behavior asArray.prototype.some).
- If not, it throws a
- Iterates through the array
- Calls
callbackfor each element with(element, index, array). - Uses
.call(thisArg, ...)to bind the optionalthisArg.
- Calls
- Returns early if a match is found
- If
callbackreturnstrue,customSomeimmediately returnstrue.
- If
- Returns
falseif no match is found- If no element passes the test,
customSomereturnsfalseafter the loop.
- If no element passes the test,
Edge Cases Handled
β Empty array always returns false
β Works with thisArg binding
β Stops checking as soon as one match is found (Optimized)
β Throws an error if callback is not a function
This version is simple, efficient, and follows the behavior of Array.prototype.some exactly.
Quick Quiz
Test your understanding with 3 quick questions
Q1What does `[].customSome(x => x > 0)` return?
Q2When does `some()` return `true`?
Q3What is the key difference between `some()` and `every()`?