From 0d8d098995f60bd91c3af5ce977160f9699dcc7e Mon Sep 17 00:00:00 2001 From: Mohammad Adnan <111442736+Mohammadadnan07@users.noreply.github.com> Date: Wed, 31 Jan 2024 12:50:27 +0530 Subject: [PATCH] Update index.js --- index.js | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 0f4b28b..afebda5 100644 --- a/index.js +++ b/index.js @@ -1,17 +1,53 @@ class SortedList { - constructor() {} + // constructor() {} + constructor() { + this.items = []; + this.length = 0; + } add(item) {} + add(item) { + this.items.push(item); + this.items.sort((a, b) => a - b); + this.length = this.items.length; + } get(pos) {} + get(pos) { + if (pos < 0 || pos >= this.length) { + throw new Error('OutOfBounds'); + } + return this.items[pos]; + } max() {} + max() { + if (this.length === 0) { + throw new Error('EmptySortedList'); + } + return this.items[this.length - 1]; + } min() {} + min() { + if (this.length === 0) { + throw new Error('EmptySortedList'); + } + return this.items[0]; + } sum() {} + sum() { + return this.items.reduce((acc, curr) => acc + curr, 0); + } avg() {} + avg() { + if (this.length === 0) { + throw new Error('EmptySortedList'); + } + return this.sum() / this.length; + } } module.exports = SortedList;