diff --git a/index.js b/index.js index 0f4b28b..d61df0f 100644 --- a/index.js +++ b/index.js @@ -1,17 +1,53 @@ class SortedList { - 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) {} + } - max() {} + get(pos) { + if (pos < 0 || pos>= this.length) { + throw new Error("OutOfBounds") + } + return this.items[pos]; + } - min() {} + max() { + if(this.length === 0){ + throw new Error('EmptySortedList'); + } + return this.items[this.length -1 ]; + } - sum() {} + min() { + if (this.length === 0){ + throw new Error("EmptySortedList") + } + return this.items[0]; + } - avg() {} + sum() { + if (this.length === 0){ + return 0;//returns 0 if the list is empty + } + return this.items.reduce((acc, curr) => acc + curr, 0)//calculation of sum using reduce + + } + + avg() { + if(this.length === 0){ + throw new Error('EmptySortedList'); + } + return this.items.reduce((acc,curr) =>acc + curr ,0 )/this.length//claculation of the average + } } module.exports = SortedList; diff --git a/index.txt b/index.txt new file mode 100644 index 0000000..d22e874 --- /dev/null +++ b/index.txt @@ -0,0 +1,36 @@ +class SortedList { + constructor(arr) { + this.items =arr ; + this.length= 0; + this.number= null; + } + + add(item) { + this.items.sort() + for(let i =0; i < this.items.length;i++){ + + if(this.items[i] <= item){ + this.number = this.items[i] + } + } + console.log(this.number) + let Nindex = this.items.indexOf(this.number) + this.items.splice(Nindex+1,0,item) + + } + + get(pos) {} + + max() {} + + min() {} + + sum() {} + + avg() {} +} +let alfie = new SortedList([9, 3, 5,2]) +alfie.add(0) +console.log(alfie.items); + +// module.exports = SortedList; diff --git a/package.json b/package.json index 2940292..c952e46 100644 --- a/package.json +++ b/package.json @@ -12,5 +12,8 @@ "intro" ], "author": "supoort@rootlearn.com", - "license": "MIT" + "license": "MIT", + "dependencies": { + "mocha": "^10.3.0" + } }