Skip to content

Commit

Permalink
fix: throw if average called with empty array
Browse files Browse the repository at this point in the history
  • Loading branch information
matejchalk committed Jun 17, 2024
1 parent 52a0f31 commit 6f91ba2
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ export function sum(values) {
* @returns {number} Average of all numbers.
*/
export function average(values) {
if (values.length === 0) {
throw new Error('Cannot calculate average from empty array');
}
return sum(values) / values.length;
}

Expand Down
7 changes: 7 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ describe('average', () => {
it('should calculate average', () => {
assert.strictEqual(average([1, 2, 3, 4]), 2.5);
});

it('should throw for empty array', () => {
assert.throws(
() => average([]),
'Cannot calculate average for empty array'
);
});
});

describe('sort', () => {
Expand Down

0 comments on commit 6f91ba2

Please sign in to comment.