Skip to content

Commit f928482

Browse files
Alex JamshidiAlex Jamshidi
authored andcommitted
added solution to tally.js
1 parent 5567875 commit f928482

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

Sprint-2/implement/tally.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1-
function tally() {}
1+
function tally(array) {
2+
if (!Array.isArray(array)) {throw new Error("Invalid array");}
3+
tally = {}
4+
array.forEach((item) =>{
5+
if (item in tally) {tally[item] += 1}
6+
else tally[item] = 1;
7+
})
8+
return tally
9+
}
210

311
module.exports = tally;
12+

Sprint-2/implement/tally.test.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,31 @@ const tally = require("./tally.js");
2020
// When passed an array of items
2121
// Then it should return an object containing the count for each unique item
2222

23+
describe("tally", () => {
2324
// Given an empty array
2425
// When passed to tally
2526
// Then it should return an empty object
26-
test.todo("tally on an empty array returns an empty object");
27+
it("tally on an empty array returns an empty object", () => {
28+
const array = [];
29+
expect(tally(array)).toEqual({})
30+
});
31+
2732

2833
// Given an array with duplicate items
2934
// When passed to tally
3035
// Then it should return counts for each unique item
36+
it("tally returns counts for each unique item", () => {
37+
const array = ['a', 'a', 'b', 'c'];
38+
expect(tally(array)).toEqual({ a : 2, b: 1, c: 1 })
39+
});
40+
3141

3242
// Given an invalid input like a string
3343
// When passed to tally
3444
// Then it should throw an error
45+
it("tally on an empty array returns an empty object", () => {
46+
const array = "string";
47+
expect(() => {tally(array);}).toThrow("Invalid array")
48+
});
49+
});
50+

0 commit comments

Comments
 (0)