Skip to content

Commit 31202c8

Browse files
committed
Refactor tally function to use Object.create(null) for counts; add test for handling prototype keywords correctly
1 parent 943226e commit 31202c8

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

Sprint-2/implement/tally.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ function tally(list) {
33
throw new Error("Input must be an array");
44
}
55

6-
const counts = {};
6+
const counts = Object.create(null);
77

88
for (const item of list) {
99
if (counts[item]) {

Sprint-2/implement/tally.test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,14 @@ test("tally counts duplicate items correctly", () => {
4848
test("tally throws an error for invalid input", () => {
4949
expect(() => tally("not an array")).toThrow("Input must be an array");
5050
});
51+
52+
// Given an array with keywords that are also properties of Object.prototype, like "toString"
53+
// When passed to tally
54+
// Then it should count them correctly without being affected by the prototype chain
55+
56+
test("tally handles prototype keywords correctly", () => {
57+
const input = ["toString", "toString", "valueOf"];
58+
const expectedOutput = { toString: 2, valueOf: 1 };
59+
60+
expect(tally(input)).toEqual(expectedOutput);
61+
});

0 commit comments

Comments
 (0)