diff --git a/index.js b/index.js index 0f4b28b4..c971f628 100644 --- a/index.js +++ b/index.js @@ -1,17 +1,50 @@ class SortedList { - constructor() {} + constructor() { + this.items = []; + this.length = this.items.length; + } - add(item) {} + add(item) { + if (typeof item === "number") { + this.items.push(item); + this.items.sort((a, b) => a - b); + this.length = this.items.length; + } + } - get(pos) {} + get(pos) { + if (pos >= this.length || pos < 0) { + throw new Error("OutOfBounds"); + } + return this.items[pos]; + } - max() {} + max() { + if (!this.length) { + throw new Error("EmptySortedList"); + } + return Math.max(...this.items); + } - min() {} + min() { + if (!this.length) { + throw new Error("EmptySortedList"); + } + return Math.min(...this.items); + } - sum() {} + sum() { + return this.items.reduce((sum, number) => sum + number, 0); + } - avg() {} + avg() { + if (!this.length) { + throw new Error("EmptySortedList"); + } + return +( + this.items.reduce((sum, number) => sum + number, 0) / this.length + ).toFixed(1); + } } module.exports = SortedList; diff --git a/package.json b/package.json index 3a5127ae..701007ec 100644 --- a/package.json +++ b/package.json @@ -19,5 +19,8 @@ "intro" ], "author": "fer@ironhack.com", - "license": "MIT" + "license": "MIT", + "dependencies": { + "mocha": "^11.7.6" + } } diff --git a/test/index.spec.js b/test/index.spec.js index 5cf5d238..8323223e 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -58,7 +58,7 @@ describe("SortedList", () => { list.get(4); }, Error, - "OutOfBounds" + "OutOfBounds", ); }); @@ -73,13 +73,13 @@ describe("SortedList", () => { list = new SortedList(); }); - it("should throw an Empty SortedList error if there are no elements in the list", () => { + it("should throw an EmptySortedList error if there are no elements in the list", () => { assert.throws( () => { list.max([]); }, Error, - "Empty SortedList" + "EmptySortedList", ); }); @@ -102,7 +102,7 @@ describe("SortedList", () => { list.min([]); }, Error, - "EmptySortedList" + "EmptySortedList", ); }); @@ -143,7 +143,7 @@ describe("SortedList", () => { list.avg([]); }, Error, - "EmptySortedList" + "EmptySortedList", ); });