Skip to content

Commit 2c0a94c

Browse files
author
JorvanW
committed
added code and tests for tally.test and js
1 parent 827b052 commit 2c0a94c

2 files changed

Lines changed: 39 additions & 2 deletions

File tree

‎Sprint-2/implement/tally.js‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,28 @@
1-
function tally() {}
1+
function tally(array) { //(array) is the input to the function
2+
3+
if (!Array.isArray(array)){ //checking if array is actually an array
4+
throw new Error("Input must be an array");
5+
}
6+
7+
if (array.length === 0){ //if array is empty return a empty array
8+
return []
9+
}
10+
11+
12+
const result = {} //creates result as an empty object which will store the counts
13+
14+
15+
for (const item of array){ //'for' loops through every item in the array
16+
if (result[item]){ // checks if the item is already in the result{}
17+
result[item]++} // If it is then '++' tells it to add 1 to the value
18+
19+
else {
20+
result[item] = 1; // else is saying that if it doesn't exist then we give it a value of 1
21+
}
22+
23+
}
24+
25+
return result;
26+
}
227

328
module.exports = tally;

‎Sprint-2/implement/tally.test.js‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,28 @@ const tally = require("./tally.js");
1919
// Given a function called tally
2020
// When passed an array of items
2121
// Then it should return an object containing the count for each unique item
22+
test("tally should return an count of each item passed through an array ",() => {
23+
expect(tally(['a', 'b', 'c'])).toEqual({a: 1, b: 1, c: 1});
24+
});
2225

2326
// Given an empty array
2427
// When passed to tally
2528
// Then it should return an empty object
26-
test.todo("tally on an empty array returns an empty object");
29+
test("tally on an empty array returns an empty object",() => {
30+
expect(tally([])).toEqual([]);
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+
test("tally on an array with duplicate items return a count for each item ",() => {
37+
expect(tally(['a', 'a', 'b', 'c'])).toEqual({a: 2, b: 1, c: 1});
38+
});
3139

3240
// Given an invalid input like a string
3341
// When passed to tally
3442
// Then it should throw an error
43+
test("tally with a invalid string should throw an error",() => {
44+
expect(tally('car'))
45+
.toThrow("Input must be an array");
46+
});

0 commit comments

Comments
 (0)