Created
November 11, 2019 17:25
-
-
Save josecarneiro/6e7ebba795b1924480d7d392d4709d3a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 = this.items.length; | |
} | |
add(item) { | |
this.items.push(item); | |
this.items.sort((a, b) => a - b); | |
this.length = this.items.length; | |
} | |
get(pos) { | |
if (pos >= 0 && pos < this.length) { | |
return this.items[pos]; | |
} else { | |
throw new Error('OutOfBounds'); | |
} | |
} | |
max() { | |
if (this.items.length === 0) { | |
throw new Error('EmptySortedList'); | |
} else { | |
return Math.max(...this.items); | |
} | |
} | |
min() { | |
if (this.items.length === 0) { | |
throw new Error('EmptySortedList'); | |
} else { | |
return this.items[0]; | |
} | |
} | |
sum() { | |
const total = this.items.reduce((accumulator, value) => accumulator + value, 0); | |
return total; | |
} | |
average() { | |
if (this.length === 0) { | |
throw new Error('EmptySortedList'); | |
} | |
const average = this.sum() / this.length; | |
return average; | |
} | |
} | |
module.exports = SortedList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment