Created
March 24, 2022 18:16
-
-
Save josecarneiro/623df8a08409ba22abaf2773187b7b7b 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) => { | |
if (a > b) { | |
return 1; | |
} else if (a < b) { | |
return -1; | |
} else { | |
return 0; | |
} | |
}); | |
// this.items.sort((a, b) => a - b); | |
this.length = this.items.length; | |
} | |
get(pos) { | |
if (pos > this.items.length - 1) { | |
throw new Error('OutOfBounds'); | |
} else { | |
return this.items[pos]; | |
} | |
} | |
max() { | |
if (this.length === 0) { | |
throw new Error('EmptySortedList'); | |
} else { | |
return this.items[this.length - 1]; | |
} | |
} | |
min() { | |
if (!this.length) { | |
throw new Error('EmptySortedList'); | |
} else { | |
return this.items[0]; | |
} | |
} | |
sum() { | |
return this.items.reduce((total, value) => { | |
return total + value; | |
}, 0); | |
} | |
avg() { | |
if (this.length === 0) { | |
throw new Error('EmptySortedList'); | |
} else { | |
return this.sum() / this.length; | |
} | |
} | |
} | |
module.exports = SortedList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment