Sobes.tech
Middle

/* Write a polyfill for Array.prototype.some Parameters - callback - a function to check each element, takes three arguments: - element - the current array element being processed. - index (optional) - the index of the current element. - array (optional) - the array being traversed. - thisArg (optional) - the value to use as this when executing callback. Return value true if the check function returns a truthy value for at least one element, otherwise false. */ Array.prototype.some = function (callback, thisArgs) { const array = this; for (let i = 0; i < array.length; i++) { if (!(i in array)) continue; const result = callback.call(thisArgs, array[i], i, array); if (result) return true; } return false; }

sobes.tech AI

Answer from AI

The polyfill for Array.prototype.some is implemented correctly. Here is an example with explanations:

Array.prototype.some = function (callback, thisArg) {
    const array = this;

    for (let i = 0; i < array.length; i++) {
        // Check if the element with index i exists (for sparse arrays)
        if (!(i in array)) continue;

        // Call callback with the correct this and arguments
        const result = callback.call(thisArg, array[i], i, array);

        // If callback returns a truthy value, return true
        if (result) return true;
    }

    // If callback did not return true for any element, return false
    return false;
};

Example usage:

const arr = [1, 2, 3, 4];
const hasEven = arr.some(num => num % 2 === 0); // true

This polyfill accounts for:

  • Missing elements in the array (sparse arrays)
  • The context of thisArg
  • Returns true on the first successful match
  • Returns false if no element satisfies the condition