Skip to content

Commit ce21823

Browse files
committed
Implement tally function and tests
1 parent de8ca14 commit ce21823

2 files changed

Lines changed: 52 additions & 29 deletions

File tree

Sprint-2/implement/tally.js

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,33 @@
1-
function tally() {}
1+
/**
2+
* tally()
3+
*
4+
* Counts how many times each item appears in an array.
5+
*
6+
* Example:
7+
* tally(['a','a','b','c'])
8+
* returns { a: 2, b: 1, c: 1 }
9+
*/
10+
11+
function tally(items) {
12+
// Validate input
13+
if (!Array.isArray(items)) {
14+
throw new Error("Expected an array");
15+
}
16+
17+
const counts = {};
18+
19+
// Loop through each item in the array
20+
for (const item of items) {
21+
// If the item already exists in the object, increase the count
22+
if (counts[item]) {
23+
counts[item] += 1;
24+
} else {
25+
// Otherwise initialise it
26+
counts[item] = 1;
27+
}
28+
}
29+
30+
return counts;
31+
}
232

333
module.exports = tally;

Sprint-2/implement/tally.test.js

Lines changed: 21 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,27 @@
11
const tally = require("./tally.js");
22

3-
/**
4-
* tally array
5-
*
6-
* In this task, you'll need to implement a function called tally
7-
* that will take a list of items and count the frequency of each item
8-
* in an array
9-
*
10-
* For example:
11-
*
12-
* tally(['a']), target output: { a: 1 }
13-
* tally(['a', 'a', 'a']), target output: { a: 3 }
14-
* tally(['a', 'a', 'b', 'c']), target output: { a : 2, b: 1, c: 1 }
15-
*/
3+
describe("tally()", () => {
4+
test("returns an empty object for an empty array", () => {
5+
expect(tally([])).toEqual({});
6+
});
167

17-
// Acceptance criteria:
8+
test("counts a single item", () => {
9+
expect(tally(["a"])).toEqual({ a: 1 });
10+
});
1811

19-
// Given a function called tally
20-
// When passed an array of items
21-
// Then it should return an object containing the count for each unique item
12+
test("counts repeated items", () => {
13+
expect(tally(["a", "a", "a"])).toEqual({ a: 3 });
14+
});
2215

23-
// Given an empty array
24-
// When passed to tally
25-
// Then it should return an empty object
26-
test.todo("tally on an empty array returns an empty object");
16+
test("counts multiple different items", () => {
17+
expect(tally(["a", "a", "b", "c"])).toEqual({
18+
a: 2,
19+
b: 1,
20+
c: 1,
21+
});
22+
});
2723

28-
// Given an array with duplicate items
29-
// When passed to tally
30-
// Then it should return counts for each unique item
31-
32-
// Given an invalid input like a string
33-
// When passed to tally
34-
// Then it should throw an error
24+
test("throws an error for invalid input", () => {
25+
expect(() => tally("not-an-array")).toThrow();
26+
});
27+
});

0 commit comments

Comments
 (0)