-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrefill an Array.js
More file actions
36 lines (26 loc) · 1.16 KB
/
Copy pathPrefill an Array.js
File metadata and controls
36 lines (26 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* Create the function prefill that returns an array of n elements that all have the same value v. See if you can do this without using a loop.
You have to validate input:
v can be anything (primitive or otherwise)
if v is ommited, fill the array with undefined
if n is 0, return an empty array
if n is anything other than an integer or integer-formatted string (e.g. '123') that is >=0, throw a TypeError
When throwing a TypeError, the message should be n is invalid, where you replace n for the actual value passed to the function.
Code Examples
prefill(3,1) --> [1,1,1]
prefill(2,"abc") --> ['abc','abc']
prefill("1", 1) --> [1]
prefill(3, prefill(2,'2d'))
--> [['2d','2d'],['2d','2d'],['2d','2d']]
prefill("xyz", 1)
--> throws TypeError with message "xyz is invalid" */
function prefill(n, v = undefined) {
if (n === 0) return []
if (parseInt(n) >= 0 && parseInt(n) == parseFloat(n))
return new Array(parseInt(n)).fill(v)
else throw new TypeError(`${n} is invalid`)
}
console.log(prefill(3, 1))
console.log(prefill(2, 'abc'))
console.log(prefill('1', 1))
console.log(prefill(3, prefill(2, '2d')))
console.log(prefill('xyz', 1))