Skip to content

Commit f1a4245

Browse files
committed
Implement tally and add tests
1 parent 9c11525 commit f1a4245

2 files changed

Lines changed: 30 additions & 3 deletions

File tree

‎Sprint-2/implement/tally.js‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,18 @@
1-
function tally() {}
1+
function tally(items) {
2+
if (!Array.isArray(items)) {
3+
throw new Error("Input must be an array");
4+
}
5+
6+
const counts = {};
7+
8+
for (const item of items) {
9+
if (counts[item] === undefined) {
10+
counts[item] = 1;
11+
} else {
12+
counts[item] = counts[item] + 1;
13+
}
14+
}
15+
return counts;
16+
}
217

318
module.exports = tally;

‎Sprint-2/implement/tally.test.js‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,24 @@ const tally = require("./tally.js");
2323
// Given an empty array
2424
// When passed to tally
2525
// Then it should return an empty object
26-
test.todo("tally on an empty array returns an empty object");
27-
26+
test("tally on an empty array returns an empty object", () => {
27+
expect(tally([])).toEqual({});
28+
});
2829
// Given an array with duplicate items
2930
// When passed to tally
3031
// Then it should return counts for each unique item
32+
test("tally counts duplicate items", () => {
33+
expect(tally(["a", "a", "b", "c"])).toEqual({
34+
a: 2,
35+
b: 1,
36+
c: 1,
37+
});
38+
});
3139

3240
// Given an invalid input like a string
3341
// When passed to tally
3442
// Then it should throw an error
43+
test("tally throws an error for invalid input", () => {
44+
expect(() => tally("hello")).toThrow();
45+
});
46+

0 commit comments

Comments
 (0)