From 6f91ba2275960f6bd197c7946860e0224175b0a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Chalk?= Date: Mon, 17 Jun 2024 14:32:59 +0200 Subject: [PATCH] fix: throw if average called with empty array --- src/index.js | 3 +++ test/index.test.js | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/src/index.js b/src/index.js index d2f047e..30d8f45 100644 --- a/src/index.js +++ b/src/index.js @@ -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; } diff --git a/test/index.test.js b/test/index.test.js index 3eea261..97078cf 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -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', () => {