➡️ Array.prototype.unshift() Polyfill
Category: js / polyfills
Difficulty: hard
The unshift() method adds one or more elements to the beginning of an array and returns the new length. ✅ Implementation [code example] How It Works Shifts existing elements to the right Loops backward to prevent overwriting elements. Moves each element to a new position based on the number of elements being added. Inserts new elements at the beginning Loops forward to place new elements in their correct positions. Returns the new array length Mimics unshift() behavior by returning the updated length. Edge Cases Handled ✔ Works with multiple elements: customUnshift(4, 5, 6) ✔ Works with empty arrays: [].customUnshift(1, 2, 3) ✔ Works with no arguments: array.customUnshift() (returns unchanged length) ✔ Preserves element order correctly This implementation is efficient and follows the exact behavior of Array.prototype.unshift. <!-- quiz-start --> Q1: What does unshift() return? [ ] The added elements [ ] The original array [x] The new length of the array [ ] undefined Q2: What is the time complexity of unshift()? [ ] O(1) [x] O(n) [ ] O(log n) [ ] O(n^2) Q3: Where does unshift() add the new elements? [x] At the beginning of the array [ ] At the end of the array [ ] At a random position [ ] Sorted into the correct position <!-- quiz-end -->...