The filter() method creates a new array with all elements that pass the test implemented by the provided callback function. This polyfill replicates the native behavior, including support for thisArg and proper handling of sparse arrays.
β Implementation
Array.prototype.myFilter = function(callback, thisArg) { if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } let result = []; for (let i = 0; i < this.length; i++) { if (this.hasOwnProperty(i)) { // Ensures only actual elements are processed if (callback.call(thisArg, this[i], i, this)) { result.push(this[i]); } } } return result; };
Example Usage:
const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.myFilter(num => num % 2 === 0); console.log(evenNumbers); // Output: [2, 4, 6]
Key Features of This Polyfill:
- Prototype Extension :
- The
myFiltermethod is added toArray.prototype, making it available on all arrays.
- Callback Execution :
- The callback function is executed on each array element, receiving
(element, index, array)as arguments. - This allows the callback to inspect the element, index, and the entire array.
- Handling
thisArg:
- The
thisArgparameter is used to bind a customthiscontext when executing the callback function.
- Sparse Array Handling :
- The method uses
this.hasOwnProperty(i)to ensure that only actual elements are processed. - This prevents issues when working with sparse arrays or arrays with holes, ensuring only the array's own properties are considered (ignoring inherited properties).
- Type Checking :
- The method checks if the
callbackargument is a valid function. - If not, it throws a
TypeError, mimicking the behavior of the nativeArray.prototype.filtermethod.
This polyfill behaves similarly to the native Array.prototype.filter, allowing for array filtering based on a custom condition. It handles thisArg, ensures correct element processing in sparse arrays, and performs type checking on the callback.
Quick Quiz
Test your understanding with 3 quick questions
Q1What does `filter()` return?
Q2Why does the filter polyfill use `this.hasOwnProperty(i)`?
Q3What does `[1, 2, 3].myFilter(x => x > 5)` return?