// Map implementation
Array.prototype.myMap = function(callback) {
const newArray = [];
for (let i = 0; i < this.length; i++) {
newArray.push(callback(this[i], i, this));
}
return newArray;
};
// Filter implementation
Array.prototype.myFilter = function(callback) {
const newArray = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
newArray.push(this[i]);
}
}
return newArray;
};
// Find implementation
Array.prototype.myFind = function(callback) {
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
return this[i];
}
}
return undefined;
};
// Example usage:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.myMap(number => number * 2);
console.log("myMap:", doubled); // Output: [2, 4, 6, 8, 10]
const evens = numbers.myFilter(number => number % 2 === 0);
console.log("myFilter:", evens); // Output: [2, 4]
const firstEven = numbers.myFind(number => number % 2 === 0);
console.log("myFind:", firstEven); // Output: 2
const firstLarge = numbers.myFind(number => number > 10);
console.log("myFind:", firstLarge); // Output: undefined
// Important Note about modifying Array.prototype:
// While the above code directly modifies the Array.prototype, it's generally discouraged in production code due to potential naming conflicts with other libraries or future JavaScript updates. It's safer to create standalone functions instead:
function myMap(arr, callback) {
const newArray = [];
for (let i = 0; i < arr.length; i++) {
newArray.push(callback(arr[i], i, arr));
}
return newArray;
}
function myFilter(arr, callback) {
const newArray = [];
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i], i, arr)) {
newArray.push(arr[i]);
}
}
return newArray;
}
function myFind(arr, callback) {
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i], i, arr)) {
return arr[i];
}
}
return undefined;
}
const doubled2 = myMap(numbers, number => number * 3);
console.log("standalone myMap:", doubled2); // Output: [3, 6, 9, 12, 15]
const evens2 = myFilter(numbers, number => number % 2 === 0);
console.log("standalone myFilter:", evens2); // Output: [2, 4]
const firstEven2 = myFind(numbers, number => number % 2 === 0);
console.log("standalone myFind:", firstEven2); // Output: 2
This improved answer provides both methods of implementation (modifying Array.prototype
and standalone functions) and explains why standalone functions are generally preferred. It also includes more comprehensive example usage and clear comments. This makes the code more robust, understandable, and maintainable.