Skip to content

Commit bc80349

Browse files
committed
refactored tally to use a non mutatitng way of calculating frequency of items in an array.
1 parent dcb2cbb commit bc80349

File tree

1 file changed

+7
-31
lines changed

1 file changed

+7
-31
lines changed

Sprint-2/implement/tally.js

Lines changed: 7 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,13 @@
11
function tally(inputArray) {
2-
if (Array.isArray(inputArray)) {
3-
if (inputArray.length === 0) {
4-
return {};
5-
}
6-
7-
let itemCount = 0;
8-
const tallyObject = {};
9-
let n = 0;
10-
11-
while (inputArray.length > 0) {
12-
itemCount = 0;
13-
const tempArray = [];
14-
let i = 0;
15-
let currentArrayItem = inputArray[0];
16-
17-
while (i < inputArray.length) {
18-
if (currentArrayItem === inputArray[i]) {
19-
itemCount++;
20-
tempArray.push(inputArray.splice(i, 1));
21-
i--;
22-
}
23-
24-
if (itemCount > 0) {
25-
tallyObject[currentArrayItem] = itemCount;
26-
}
27-
28-
i++;
29-
}
30-
}
31-
return tallyObject;
32-
} else {
2+
if (!Array.isArray(inputArray)) {
333
throw new Error("error invalid input passed, please provide an array");
344
}
5+
6+
const tallyObject = {};
7+
for (const item of inputArray) {
8+
tallyObject[item] = (tallyObject[item] || 0) + 1;
9+
}
10+
return tallyObject;
3511
}
3612

3713
module.exports = tally;

0 commit comments

Comments
 (0)