From 0b63649557da07c270d1ef789195289457c9172d Mon Sep 17 00:00:00 2001 From: KhotKeys Date: Fri, 7 Aug 2026 16:06:31 +0100 Subject: [PATCH] implement sum function and tests --- Sprint-1/implement/sum.js | 1 + Sprint-1/implement/sum.test.js | 34 ++++++++++++++++++---------------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/Sprint-1/implement/sum.js b/Sprint-1/implement/sum.js index 9062aafe3..6230724e3 100644 --- a/Sprint-1/implement/sum.js +++ b/Sprint-1/implement/sum.js @@ -1,4 +1,5 @@ function sum(elements) { + return elements.filter(n => typeof n === "number").reduce((acc, n) => acc + n, 0); } module.exports = sum; diff --git a/Sprint-1/implement/sum.test.js b/Sprint-1/implement/sum.test.js index dd0a090ca..cff277f5f 100644 --- a/Sprint-1/implement/sum.test.js +++ b/Sprint-1/implement/sum.test.js @@ -13,24 +13,26 @@ const sum = require("./sum.js"); // Given an empty array // When passed to the sum function // Then it should return 0 -test.todo("given an empty array, returns 0") +test("given an empty array, returns 0", () => { + expect(sum([])).toEqual(0); +}); -// Given an array with just one number -// When passed to the sum function -// Then it should return that number +test("given an array with just one number, returns that number", () => { + expect(sum([42])).toEqual(42); +}); -// Given an array containing negative numbers -// When passed to the sum function -// Then it should still return the correct total sum +test("given an array containing negative numbers, returns the correct total", () => { + expect(sum([10, -5, 3])).toEqual(8); +}); -// Given an array with decimal/float numbers -// When passed to the sum function -// Then it should return the correct total sum +test("given an array with decimal numbers, returns the correct total", () => { + expect(sum([1.5, 2.5])).toEqual(4); +}); -// Given an array containing non-number values -// When passed to the sum function -// Then it should ignore the non-numerical values and return the sum of the numerical elements +test("given an array containing non-number values, ignores them and sums the rest", () => { + expect(sum(["hey", 10, "hi", 60, 10])).toEqual(80); +}); -// Given an array with only non-number values -// When passed to the sum function -// Then it should return the least surprising value given how it behaves for all other inputs +test("given an array with only non-number values, returns 0", () => { + expect(sum(["a", "b"])).toEqual(0); +});