diff --git a/index.js b/index.js index 0f4b28b4..8e2c02e2 100644 --- a/index.js +++ b/index.js @@ -1,17 +1,64 @@ class SortedList { - constructor() {} + constructor() { + this.items = []; + this.length = this.items.length; + } - add(item) {} + add(item) { + this.items.push(item); + if (this.length > 1) { + this.length = this.items.length; + return this.items.sort((a, b) => a - b); + } else { + this.length = this.items.length; + return this.items; + } + } - 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 Math.max(...this.items); + } + } - min() {} + min() { + if (this.length === 0) { + throw new Error('EmptySortedList'); + } else { + return Math.min(...this.items); + } + } - sum() {} + sum() { + if (this.length === 0) { + return 0; + } else { + return this.items.reduce((sum, val) => { + return (sum += val); + }); + } + } - avg() {} + avg() { + if (this.length === 0) { + throw new Error('EmptySortedList'); + } else { + const total = this.items.reduce((sum, val) => { + return (sum += val); + }); + return total / this.length; + } + } } module.exports = SortedList; diff --git a/package.json b/package.json index 3a5127ae..932523a5 100644 --- a/package.json +++ b/package.json @@ -19,5 +19,8 @@ "intro" ], "author": "fer@ironhack.com", - "license": "MIT" + "license": "MIT", + "dependencies": { + "mocha": "^11.1.0" + } }