Last active
November 5, 2019 19:27
-
-
Save sandrabosk/1dc434be87b4efc03238e53ffae1376f 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
// 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