JavaScript Array Filler
Your task is to create a JavaScript function that efficiently fills a new array with a specified value. This is a common operation in programming for initializing arrays with default data or preparing them for further processing.
Problem Description
You need to implement a JavaScript function named fillArray that accepts two arguments:
size: A non-negative integer representing the desired number of elements in the array.value: The value that each element of the array should contain. This can be any JavaScript data type (number, string, boolean, object, null, undefined, etc.).
The function should return a new array of the specified size, where every element is equal to the provided value.
Key Requirements:
- The function must create and return a new array. It should not modify any existing arrays.
- The array must have exactly
sizeelements. - Each element in the returned array must be strictly equal (
===) to thevalueargument.
Expected Behavior:
- If
sizeis 0, an empty array should be returned. - The function should handle various data types for the
valueargument correctly.
Edge Cases:
- What happens if
sizeis negative? (The constraints will address this). - What happens if
valueisnullorundefined?
Examples
Example 1:
Input: size = 5, value = 0
Output: [0, 0, 0, 0, 0]
Explanation: A new array of size 5 is created, and each element is filled with the value 0.
Example 2:
Input: size = 3, value = "hello"
Output: ["hello", "hello", "hello"]
Explanation: A new array of size 3 is created, and each element is filled with the string "hello".
Example 3:
Input: size = 0, value = 100
Output: []
Explanation: When the size is 0, an empty array is returned, regardless of the value.
Example 4:
Input: size = 2, value = { name: "test" }
Output: [{ name: "test" }, { name: "test" }]
Explanation: Each element in the new array refers to the same object instance provided as the value.
Constraints
0 <= size <= 10000(The number of elements will be within this range.)sizewill always be an integer.valuecan be any valid JavaScript data type.- The solution should be reasonably efficient, aiming for a time complexity of O(n) where n is the
sizeof the array.
Notes
Consider different ways to create and populate arrays in JavaScript. There are built-in methods that can be very helpful here. Think about immutability – ensuring you are not altering any existing data structures.