Implement Array.prototype.drop
Implement a function that mimics the behavior of Array.prototype.drop in JavaScript. This function should create a shallow copy of an array, omitting the first n elements.
Problem Description
Your task is to create a standalone JavaScript function named drop that accepts two arguments: an array and a number n. The function should return a new array containing all elements from the input array except for the first n elements.
Key Requirements:
- The original array must not be modified.
- The function should return a new array.
- If
nis not provided, it should default to1. - If
nis less than or equal to0, the function should return a shallow copy of the entire original array. - If
nis greater than or equal to the length of the array, the function should return an empty array.
Expected Behavior:
The drop(array, n) function will take an array and an optional n (the number of elements to drop from the beginning). It will return a new array with those elements removed.
Examples
Example 1:
Input: drop([1, 2, 3], 2)
Output: [3]
Explanation: We drop the first 2 elements from the array [1, 2, 3], leaving [3].
Example 2:
Input: drop([1, 2, 3], 0)
Output: [1, 2, 3]
Explanation: Since n is 0, no elements are dropped, and a shallow copy of the original array is returned.
Example 3:
Input: drop([1, 2, 3])
Output: [2, 3]
Explanation: n is not provided, so it defaults to 1. The first element is dropped.
Example 4:
Input: drop([1, 2, 3], 5)
Output: []
Explanation: n is greater than the array length, so an empty array is returned.
Example 5:
Input: drop([], 2)
Output: []
Explanation: Dropping elements from an empty array results in an empty array.
Constraints
- The input
arraywill always be a valid JavaScript array. - The input
nwill be a non-negative integer orundefined. - The function should have a time complexity of O(k), where k is the number of elements remaining in the new array after dropping.
Notes
- Consider how to handle the case where
nis not provided. - Think about efficient ways to create a shallow copy of the relevant portion of the array.
- This function is intended to be a standalone utility, not an addition to
Array.prototype.