In: Computer Science
JavaScript
Write a function called "first" that takes in two arguments - the first is an argument called arr that is an array of numbers, the second is an optional number argument called num(hint: you'll need a default value - look back at the slides).
If "num" was not passed in (since it's optional), the "first" function will return an array containing the first item of the array.
If a value for "num" was given, the "first" function will return an array containing the first "num" values of the array.
See the example output below.
console.log(first([7, 9, 0, -2])); // [7] console.log(first([], 3)); // [undefined, undefined, undefined] console.log(first([7, 9, 0, -2], 3)); // [7, 9, 0] console.log(first([7, 9, 0, -2], 6)); // [7, 9, 0, -2, undefined, undefined]
function first(arr,num=-1){
let out=[];
if(arr.length==0){
for(let i=0;i<num;i++){
out.push(undefined)
}
return out;
}else if(num==-1){
return arr[0];
}else if(num<=arr.length){
for(let i=0;i<num;i++){
out.push(arr[i]);
}return out
}else if(num>arr.length){
for(let i=0;i<num;i++){
if(i<arr.length){
out.push(arr[i]);
}else{
out.push(undefined);
}
}
return out;
}
}
console.log(first([7, 9, 0, -2]));
console.log(first([], 3));
console.log(first([7, 9, 0, -2], 3));
console.log(first([7, 9, 0, -2], 6));