How do you plan to implement custom versions of Array.prototype methods like flat, map, reduce, and concat in JavaScript?
Question Analysis
This question is technical and evaluates your understanding of JavaScript's Array prototype methods and your ability to implement them from scratch. You are required to demonstrate your knowledge of how these methods work internally by coding custom versions of them. This involves understanding the purpose and behavior of each method, managing array elements, and handling edge cases.
Answer
To implement custom versions of Array.prototype.flat
, map
, reduce
, and concat
in JavaScript, you need to first understand what each method does:
flat
: Flattens an array of arrays into a single array up to a specified depth.map
: Creates a new array populated with the results of calling a provided function on every element in the calling array.reduce
: Executes a reducer function (that you provide) on each element of the array, resulting in a single output value.concat
: Merges two or more arrays and returns a new array.
Here is how you can implement each of these methods:
-
Custom
flat
method:Array.prototype.customFlat = function(depth = 1) { const flatten = (arr, depth) => { if (depth < 1) return arr; return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val, depth - 1) : val), []); }; return flatten(this, depth); };
-
Custom
map
method:Array.prototype.customMap = function(callback) { const result = []; for (let i = 0; i < this.length; i++) { if (i in this) { result.push(callback(this[i], i, this)); } } return result; };
-
Custom
reduce
method:Array.prototype.customReduce = function(callback, initialValue) { let accumulator = (initialValue !== undefined) ? initialValue : this[0]; for (let i = (initialValue !== undefined) ? 0 : 1; i < this.length; i++) { if (i in this) { accumulator = callback(accumulator, this[i], i, this); } } return accumulator; };
-
Custom
concat
method:Array.prototype.customConcat = function(...args) { const result = [...this]; args.forEach(arg => { if (Array.isArray(arg)) { result.push(...arg); } else { result.push(arg); } }); return result; };
These implementations demonstrate your understanding of how each method works and handle various cases, such as nested arrays for flat
, handling of undefined
initial values for reduce
, and variable arguments for concat
. This will showcase your ability to manipulate arrays and use basic JavaScript constructs effectively.