Skip to content

Commit ae3c218

Browse files
committed
add tally
.js
1 parent dc4e5b1 commit ae3c218

2 files changed

Lines changed: 32 additions & 2 deletions

File tree

‎Sprint-2/implement/tally.js‎

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

321
module.exports = tally;

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

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,23 @@ const tally = require("./tally.js");
2424
// When passed to tally
2525
// Then it should return an empty object
2626
test.todo("tally on an empty array returns an empty object");
27-
27+
test("tally on an empty array returns an empty object", () => {
28+
expect(tally([])).toEqual({});
29+
});
2830
// Given an array with duplicate items
2931
// When passed to tally
3032
// Then it should return counts for each unique item
33+
test("tally counts duplicate items", () => {
34+
expect(tally(["a", "a", "b", "c"])).toEqual({
35+
a: 2,
36+
b: 1,
37+
c: 1,
38+
});
39+
});
3140

3241
// Given an invalid input like a string
3342
// When passed to tally
3443
// Then it should throw an error
44+
test("tally throws an error when given a string", () => {
45+
expect(() => tally("hello")).toThrow();
46+
});

0 commit comments

Comments
 (0)