From 8cea96fcbef71cbc31e1ebdc01269778bd43755c Mon Sep 17 00:00:00 2001 From: Gowtham Jangiti Date: Mon, 14 Oct 2024 18:28:09 +0530 Subject: [PATCH 1/2] Initial Setup --- index.js | 1 + 1 file changed, 1 insertion(+) diff --git a/index.js b/index.js index 0f4b28b..34875e0 100644 --- a/index.js +++ b/index.js @@ -14,4 +14,5 @@ class SortedList { avg() {} } + module.exports = SortedList; From 480764184126764d64b06337902b78464c1442cd Mon Sep 17 00:00:00 2001 From: Gowtham Jangiti Date: Mon, 14 Oct 2024 18:31:14 +0530 Subject: [PATCH 2/2] Completed --- index.js | 56 +++++++++++++++++++++++++++++++++++++++------------- package.json | 5 ++++- 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/index.js b/index.js index 34875e0..4c43497 100644 --- a/index.js +++ b/index.js @@ -1,18 +1,46 @@ class SortedList { - constructor() {} - - add(item) {} - - get(pos) {} - - max() {} - - min() {} - - sum() {} - - avg() {} + constructor() { + this.items = []; + this.length = 0; + } + + add(item) { + this.items.push(item); + this.items.sort((a, b) => (a - b)); + this.length = this.items.length; + } + + get(pos) { + if (pos < 0 || pos >= this.length) + 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 === 0) + throw new Error("EmptySortedList"); + else + return this.items[0]; + } + + sum() { + return this.items.reduce((acc, curr) => acc + curr, 0); + } + + avg() { + if (this.length === 0) + throw new Error("EmptySortedList"); + else + return this.sum() / this.length; + } } - module.exports = SortedList; diff --git a/package.json b/package.json index 2940292..d36e941 100644 --- a/package.json +++ b/package.json @@ -12,5 +12,8 @@ "intro" ], "author": "supoort@rootlearn.com", - "license": "MIT" + "license": "MIT", + "dependencies": { + "mocha": "^10.7.3" + } }