Created
September 27, 2022 16:49
-
-
Save josecarneiro/9aa26e59548e4e9a09d73453a569a9a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SortedList { | |
constructor() { | |
this.items = []; | |
this.length = 0; | |
} | |
add(item) { | |
this.items.push(item); | |
this.items.sort((a, b) => a - b); | |
this.length = this.items.length; | |
} | |
get(pos) { | |
if (pos > this.length - 1) { | |
throw new Error('OutOfBounds'); | |
} else { | |
return this.items[pos]; | |
} | |
} | |
max() { | |
if (this.length) { | |
// this.items = [ 1, 2, 3 ]; | |
// return Math.max(1, 2, 3); | |
return Math.max(...this.items); | |
} else { | |
throw new Error('EmptySortedList'); | |
} | |
} | |
min() { | |
if (this.length) { | |
return Math.min(...this.items); | |
} else { | |
throw new Error('EmptySortedList'); | |
} | |
} | |
sum() { | |
return this.items.reduce((acc, value) => acc + value, 0); | |
} | |
avg() { | |
if (this.length) { | |
return this.sum() / this.length; | |
} else { | |
throw new Error('EmptySortedList'); | |
} | |
} | |
} | |
module.exports = SortedList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment