Skip to content

Instantly share code, notes, and snippets.

@josecarneiro
Created March 24, 2022 18:16
Show Gist options
  • Save josecarneiro/623df8a08409ba22abaf2773187b7b7b to your computer and use it in GitHub Desktop.
Save josecarneiro/623df8a08409ba22abaf2773187b7b7b to your computer and use it in GitHub Desktop.
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