diff --git a/index.js b/index.js index 0f4b28b4..3a8f5b75 100644 --- a/index.js +++ b/index.js @@ -1,17 +1,65 @@ class SortedList { - constructor() {} + constructor() { + this.items = []; + this.length = 0; + } - add(item) {} + add(item) { + this.items.push(item); + this.items.sort((a, b) => { + return a - b; + }); + this.length = this.items.length; + } - get(pos) {} + get(pos) { + if (this.items[pos]) { + return this.items[pos]; + } else { + throw new Error("OutOfBounds"); + } + } - max() {} + max() { + if (this.items.length === 0) { + throw new Error("EmptySortedList"); + } else { + return this.items[this.items.length - 1]; + } + } - min() {} + min() { + if (this.items.length === 0) { + throw new Error("EmptySortedList"); + } else { + return this.items[0]; + } + } - sum() {} + sum() { + // let sum = 0; + // this.items.forEach((currentElement) => { + // sum += currentElement; + // }); + // return sum; - avg() {} + const total = this.items.reduce((acc, currentValue) => { + return acc + currentValue; + }, 0); + return total; + } + + avg() { + let sum = 0; + if (this.items.length === 0) { + throw new Error("EmptySortedList"); + } else { + this.items.forEach((currentElement) => { + sum += currentElement; + }); + } + return sum / this.items.length; + } } module.exports = SortedList; diff --git a/package.json b/package.json index 3a5127ae..f2ff4434 100644 --- a/package.json +++ b/package.json @@ -19,5 +19,8 @@ "intro" ], "author": "fer@ironhack.com", - "license": "MIT" + "license": "MIT", + "dependencies": { + "mocha": "^11.7.5" + } }