forked from ironhack-labs/lab-intro-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (49 loc) · 1.06 KB
/
index.js
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
45
46
47
48
49
50
class SortedList {
constructor() {
//Iteration 1: constructor()
this.items = [];
this.length = this.items.length;
}
//Iteration 2: add(item)
add(item) {
this.items.push(item);
this.items.sort((a, b) => a - b);
this.length = this.items.length;
}
//Iteration 3: get(pos)
get(pos) {
if (pos < this.length) {
return this.items[pos];
} else throw Error("OutOfBounds");
}
//Iteración 4: max ()
max() {
return !this.length
? (() => {
throw new Error("EmptySortedList");
})()
: Math.max(...this.items);
}
//Iteración 4: min ()
min() {
return !this.length
? (() => {
throw new Error("EmptySortedList");
})()
: Math.min(...this.items);
}
//Bonus iterations
//Iteration 6: sum()
sum() {
return this.items.reduce((acc, val) => acc + val, 0);
}
//Iteration 7: avg()
avg() {
return !this.length
? (() => {
throw new Error("EmptySortedList");
})()
: this.sum() / this.length;
}
}
module.exports = SortedList;