From b62c235be1553165f8d3f20f4c85bf2f9488dd9d Mon Sep 17 00:00:00 2001 From: Kanak sharma Date: Mon, 16 Dec 2024 12:36:32 +0530 Subject: [PATCH] Done --- index.js | 53 ++++++++++++++++++++++++++++++++++++++++++++-------- package.json | 5 ++++- 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index 0f4b28b..ae61efe 100644 --- a/index.js +++ b/index.js @@ -1,17 +1,54 @@ class SortedList { - constructor() {} + constructor() { + // Initialize the list with an empty array + this.items = []; + this.length = 0; + } - add(item) {} + // Iteration 2: Add an item while maintaining order + add(item) { + this.items.push(item); + this.items.sort((a, b) => a - b); // Sort array in ascending order + this.length = this.items.length; // Update the length property + } - get(pos) {} + // Iteration 3: Get an item at a specified position + get(pos) { + if (pos < 0 || pos >= this.length) { + throw new Error('OutOfBounds'); // Error if position is invalid + } + return this.items[pos]; // Return the element at the specified position + } - max() {} + // Iteration 4: Get the max value + max() { + if (this.length === 0) { + throw new Error('EmptySortedList'); // Error if the list is empty + } + return this.items[this.length - 1]; // The last element is the highest value in sorted list + } - min() {} + // Iteration 5: Get the min value + min() { + if (this.length === 0) { + throw new Error('EmptySortedList'); // Error if the list is empty + } + return this.items[0]; // The first element is the lowest value in sorted list + } - sum() {} + // Iteration 6: Get the sum of all elements + sum() { + return this.length === 0 ? 0 : this.items.reduce((acc, val) => acc + val, 0); // Sum all elements or return 0 if empty + } - avg() {} + // Iteration 7: Get the average of all elements + avg() { + if (this.length === 0) { + throw new Error('EmptySortedList'); // Error if the list is empty + } + return this.sum() / this.length; // Calculate average + } } -module.exports = SortedList; +module.exports = SortedList; // Export the class for testing + diff --git a/package.json b/package.json index 2940292..2aa021e 100644 --- a/package.json +++ b/package.json @@ -12,5 +12,8 @@ "intro" ], "author": "supoort@rootlearn.com", - "license": "MIT" + "license": "MIT", + "dependencies": { + "mocha": "^11.0.1" + } }