Skip to content

Commit 2253eff

Browse files
committed
tally function updated to create empty object with no inherited properties
1 parent ba22418 commit 2253eff

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

Sprint-2/implement/tally.js

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,16 @@ function tally(items) {
22
if (!Array.isArray(items)) {
33
throw new Error("Input must be an array");
44
}
5-
const counts = {}; // empty object to store tally of key-value pairs
5+
const counts = Object.create(null); // empty object to store tally of key-value pairs
6+
// object.create(null) creates a new object with no inherited properties
67
for (const item of items) {
7-
// iterates through each element in the items array
8-
if (counts[item]) {
9-
// checks if the item already exists as a key in counts object
10-
counts[item] += 1; // increments the count for that item by 1
11-
} else {
12-
counts[item] = 1; // initializes the count for that item to 1
13-
}
8+
// iterate through each item in the input array
9+
const key = String(item); // convert item to string to use as key
10+
counts[key] = (counts[key] || 0) + 1; // increment count for this key
1411
}
1512
return counts; // returns the final counts object
1613
}
1714

1815
module.exports = tally;
16+
17+
console.log(tally(["toString", "toString"]));

0 commit comments

Comments
 (0)