From f70cba405a2e64c3fcb6e8de30347bd934fe3746 Mon Sep 17 00:00:00 2001 From: VijayaAdamane <95336658+VijayaAdamane@users.noreply.github.com> Date: Sun, 18 Feb 2024 09:45:38 +0530 Subject: [PATCH] Update index.js --- index.js | 60 +++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 53 insertions(+), 7 deletions(-) diff --git a/index.js b/index.js index 0f4b28b..a0b806d 100644 --- a/index.js +++ b/index.js @@ -1,17 +1,63 @@ class SortedList { - constructor() {} + constructor() { + this.items = [], + this.length = 0 + } - add(item) {} + add(item) { + this.items.push(item); + this.length++; + this.items.sort((a, b) => { + return a - b; + }) + } - get(pos) {} + get(pos) { + if(pos >= this.length){ + throw new Error("OutofBounds"); + } + else{ + return this.items[pos]; + } + } - max() {} + max() { + if(this.length === 0){ + throw new Error('EmptySortedList'); + } + else{ + return this.items[this.length-1]; + } + } - min() {} + min() { + if(this.length === 0){ + throw new Error('EmptySortedList'); + } + else{ + return this.items[0]; + } + } - sum() {} + sum() { + if(this.length === 0){ + return 0; + } + let sum = this.items.reduce((acc, current) => { + return acc + current; + }) - avg() {} + return sum; + } + + avg() { + let sum = this.items.reduce((acc, current) => { + return acc + current; + }) + let avg = sum/this.length; + + return avg; + } } module.exports = SortedList;