Skip to content

Commit 320bf84

Browse files
committed
implemented tally function adn wrote test cases for it
1 parent b44572c commit 320bf84

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

Sprint-2/implement/tally.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,19 @@
1-
function tally() {}
1+
function tally(items) {
2+
if (!Array.isArray(items)) {
3+
throw new Error("Input must be an array");
4+
}
25

3-
module.exports = tally;
6+
const result = {};
7+
8+
for (const item of items) {
9+
if (result[item]) {
10+
result[item]++;
11+
} else {
12+
result[item] = 1;
13+
}
14+
}
15+
16+
return result;
17+
}
18+
19+
module.exports = tally;

Sprint-2/implement/tally.test.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,29 @@ const tally = require("./tally.js");
1919
// Given a function called tally
2020
// When passed an array of items
2121
// Then it should return an object containing the count for each unique item
22+
test("tally counts the frequency of each item in an array", () => {
23+
expect(tally(["a"])).toEqual({ a: 1 });
24+
expect(tally(["a", "a", "a"])).toEqual({ a: 3 });
25+
expect(tally(["a", "a", "b", "c"])).toEqual({ a: 2, b: 1, c: 1 });
26+
});
2227

2328
// Given an empty array
2429
// When passed to tally
2530
// Then it should return an empty object
26-
test.todo("tally on an empty array returns an empty object");
31+
test("tally on an empty array returns an empty object", () => {
32+
expect(tally([])).toEqual({});
33+
});
2734

2835
// Given an array with duplicate items
2936
// When passed to tally
3037
// Then it should return counts for each unique item
38+
test("tally counts duplicate items correctly", () => {
39+
expect(tally(["x", "y", "x", "z", "y"])).toEqual({ x: 2, y: 2, z: 1 });
40+
});
3141

3242
// Given an invalid input like a string
3343
// When passed to tally
3444
// Then it should throw an error
45+
test("tally throws an error for non-array input", () => {
46+
expect(() => tally("not an array")).toThrow("Input must be an array");
47+
});

0 commit comments

Comments
 (0)