From 3c9ad463126e605667fc864fe6b62ccbd2dd1b02 Mon Sep 17 00:00:00 2001 From: "github@esslinger.dev" Date: Sat, 8 Oct 2022 11:03:50 +0200 Subject: [PATCH 1/3] feat(maths): add `DigitSum` --- Maths/DigitSum.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Maths/DigitSum.ts diff --git a/Maths/DigitSum.ts b/Maths/DigitSum.ts new file mode 100644 index 00000000..1c86840e --- /dev/null +++ b/Maths/DigitSum.ts @@ -0,0 +1,23 @@ +/** + * @function DigitSum + * @description Calculate the sum of all digits of a natural number (number base 10). + * @param {number} num - A natural number. + * @return {number} - Sum of all digits of given natural number. + * @see https://en.wikipedia.org/wiki/Digit_sum + * @example Factorial(12) = 3 + * @example DigitSum(9045) = 18 + */ + +export const DigitSum = (num: number): number => { + if (num < 0 || !Number.isInteger(num)) { + throw new Error("only natural numbers are supported"); + } + + let sum = 0; + while (num != 0) { + sum += num % 10; + num = Math.floor(num / 10); + } + + return sum; +}; From 741b8bfc4482c87202f08700c6d91511652bfc69 Mon Sep 17 00:00:00 2001 From: "github@esslinger.dev" Date: Sat, 8 Oct 2022 11:04:04 +0200 Subject: [PATCH 2/3] test(maths): add `DigitSum` tests --- Maths/test/DigitSum.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Maths/test/DigitSum.test.ts diff --git a/Maths/test/DigitSum.test.ts b/Maths/test/DigitSum.test.ts new file mode 100644 index 00000000..5db9f994 --- /dev/null +++ b/Maths/test/DigitSum.test.ts @@ -0,0 +1,19 @@ +import { DigitSum } from "../DigitSum"; + +describe("DigitSum", () => { + test.each([-42, -0.1, -1, 0.2, 3.3, NaN, -Infinity, Infinity])( + "should throw an error for non natural number %d", + (num) => { + expect(() => DigitSum(num)).toThrowError( + "only natural numbers are supported", + ); + }, + ); + + test.each([[0,0], [1, 1], [12, 3], [123, 6], [9045, 18], [1234567890, 45]])( + "of %i should be %i", + (num, expected) => { + expect(DigitSum(num)).toBe(expected); + }, + ); +}); From d858493b26da611f62d8dad7eabd79b238f8ec3a Mon Sep 17 00:00:00 2001 From: "github@esslinger.dev" Date: Sat, 8 Oct 2022 11:11:31 +0200 Subject: [PATCH 3/3] chore(maths): fix jsdoc --- Maths/DigitSum.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Maths/DigitSum.ts b/Maths/DigitSum.ts index 1c86840e..65a0f3f0 100644 --- a/Maths/DigitSum.ts +++ b/Maths/DigitSum.ts @@ -4,7 +4,7 @@ * @param {number} num - A natural number. * @return {number} - Sum of all digits of given natural number. * @see https://en.wikipedia.org/wiki/Digit_sum - * @example Factorial(12) = 3 + * @example DigitSum(12) = 3 * @example DigitSum(9045) = 18 */