diff --git a/index.js b/index.js index 0f4b28b..7decd6d 100644 --- a/index.js +++ b/index.js @@ -1,17 +1,62 @@ class SortedList { - constructor() {} + constructor() { + this.items = []; + this.length = 0; +} + + add(item) + { + // Add the item and keep the list sorted + this.items.push(item); + this.items.sort((a, b) => a - b); + // Update the length + this.length = this.items.length; + } + + + get(pos) { + // Check if pos is out of bounds + if (pos < 0 || pos >= this.length) { + throw new Error('OutOfBounds'); + } + return this.items[pos]; + } + + max() { + // If the list is empty, throw an error + if (this.length === 0) { - add(item) {} + throw new Error('EmptySortedList'); + } + // Return the last element (highest value since it's sorted) + return this.items[this.length - 1]; + } - get(pos) {} + min() { + // If the list is empty, throw an error + if (this.length === 0) { + throw new Error('EmptySortedList'); + } + // Return the first element (lowest value since it's sorted) + return this.items[0]; + } - max() {} - min() {} + sum() { + // Calculate the sum using reduce + return this.items.reduce((acc, curr) => acc + curr, 0); + } - sum() {} + avg() + { + // If the list is empty, throw an error + if (this.length === 0) { + throw new Error('EmptySortedList'); + } - avg() {} + // Return the average by dividing the sum by the length + return this.sum() / this.length; + } } module.exports = SortedList; diff --git a/package.json b/package.json index 2940292..9ade1c8 100644 --- a/package.json +++ b/package.json @@ -12,5 +12,8 @@ "intro" ], "author": "supoort@rootlearn.com", - "license": "MIT" + "license": "MIT", + "dependencies": { + "mocha": "^10.8.2" + } }