Skip to content

Commit 8953ba6

Browse files
committed
Added implementation for tally
1 parent a4b781b commit 8953ba6

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

Sprint-2/implement/tally.js

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,22 @@
1-
function tally() {}
1+
function tally(arr) {
2+
// Check if the input is not an array
3+
if (!Array.isArray(arr)) {
4+
// If it's not an array, stop the function
5+
// and throw an error message
6+
throw new Error("Input must be an array");
7+
}
8+
9+
// Create an empty obkect to store our counts
10+
const counts = {};
11+
12+
// Loop through each item in the array one by one
13+
for (const item of arr) {
14+
// If the item already exists in counts, add 1 to it
15+
// If it doesn't exist yet (undefined), start it at 0 then add 1
16+
counts[item] = (counts[item] || 0) + 1;
17+
}
18+
// Return the finished counts object once all items have been tallied
19+
return counts;
20+
}
221

322
module.exports = tally;

0 commit comments

Comments
 (0)