Skip to content

Instantly share code, notes, and snippets.

@sandrabosk
Last active November 5, 2019 19:27
Show Gist options
  • Save sandrabosk/1dc434be87b4efc03238e53ffae1376f to your computer and use it in GitHub Desktop.
Save sandrabosk/1dc434be87b4efc03238e53ffae1376f to your computer and use it in GitHub Desktop.
// new SortedList should create a new object from the SortedList class
// The object should have a items and length property
// items should be an array
// length should be the number of elements in the array
class SortedList {
constructor(){
this.items = [];
this.length = this.items.length;
}
// add(x) will add x to the items array
add(item){
this.items.push(item);
this.items.sort((a, b) => {
return a - b;
});
this.length ++;
}
// The method will get the nth value in the list
// You should also provide a length property that gives the length of the list.
get(pos){
if (pos > this.length){
throw new Error("OutOfBounds");
}
return this.items[pos];
}
// Should return the max value of the array
max(){
if (this.length === 0){
throw new Error("EmptySortedList");
}
return Math.max(...this.items);
}
// Should return the lowest value of the array
min(){
if (this.length === 0) {
throw new Error("EmptySortedList");
}
return Math.min(...this.items);
}
// Should return the sum value of the array
sum(){
if (this.length === 0) {
return 0;
}
return this.items.reduce((sum, i) => {
return sum + i;
});
}
// Should return the average value of the array
avg(){
if (this.length === 0) {
throw new Error("EmptySortedList");
}
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