@lew
The unshift() method in JavaScript is used to add one or more elements to the beginning of an array. Here's how you can implement it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Array.prototype.unshift = function(...elements) { // Calculate new array length after adding elements const newLength = this.length + arguments.length; // Move existing elements to make space for new elements for (let i = newLength - 1; i >= elements.length; i--) { this[i] = this[i - elements.length]; } // Add new elements to the beginning of the array for (let i = 0; i < elements.length; i++) { this[i] = elements[i]; } return newLength; }; |
In this implementation, we extend the Array prototype and define our own implementation of the unshift() method. The method takes one or more elements as arguments and calculates the new length of the array after adding these elements.
Next, it uses a loop to move the existing elements in the array to make space for the new elements. The loop iterates backwards, starting from the new length of the array minus the number of new elements, and assigns each element to its new position in the array.
Finally, another loop is used to add the new elements to the beginning of the array by assigning them to the first few positions.
The method returns the new length of the array after adding the elements.