Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 40 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
@@ -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;
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,8 @@
"intro"
],
"author": "fer@ironhack.com",
"license": "MIT"
"license": "MIT",
"dependencies": {
"mocha": "^11.7.6"
}
}
10 changes: 5 additions & 5 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ describe("SortedList", () => {
list.get(4);
},
Error,
"OutOfBounds"
"OutOfBounds",
);
});

Expand All @@ -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",
);
});

Expand All @@ -102,7 +102,7 @@ describe("SortedList", () => {
list.min([]);
},
Error,
"EmptySortedList"
"EmptySortedList",
);
});

Expand Down Expand Up @@ -143,7 +143,7 @@ describe("SortedList", () => {
list.avg([]);
},
Error,
"EmptySortedList"
"EmptySortedList",
);
});

Expand Down