-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPickASetOfFirstElemtns.js
More file actions
44 lines (35 loc) · 1.06 KB
/
PickASetOfFirstElemtns.js
File metadata and controls
44 lines (35 loc) · 1.06 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
37
38
39
40
41
42
43
44
/*
Task:
Write a function to get the first element(s) of a sequence. Passing a parameter n (default=1) will return the first n element(s) of the sequence.
If n == 0 return an empty sequence []
Examples
var arr = ['a', 'b', 'c', 'd', 'e'];
first(arr) //=> ['a'];
first(arr, 2) //=> ['a', 'b']
first(arr, 3) //=> ['a', 'b', 'c'];
first(arr, 0) //=> [];
*/
//Answer
//P arr = seq/array, second arg 'n', number of letters, or like the end point
//R if n == 0 return empty arr [] && what mentioned before
//E
//P
// var arr = ['a', 'b', 'c', 'd', 'e'];
// first(arr) // 'a'
// first(arr, 6) // returns everything in thea arr
function first(arr, n) {
let result = [];
if (n == null) {
return [arr[0]];
} else if (n > arr.length) {
return arr;
}
for (let i = 0; i < n; i++) {
result.push(arr[i]);
}
return result;
}
console.log(first(["a", "b", "c", "d", "e"])); // ['a']
console.log(first(["a", "b", "c", "d", "e"], 1)); // ['a']
console.log(first(["a", "b", "c", "d", "e"], 4)); // ['a', 'b', 'c', 'd']
console.log(first(["a", "b", "c", "d", "e"], 0)); // []