diff --git a/Maths/DigitSum.ts b/Maths/DigitSum.ts new file mode 100644 index 00000000..65a0f3f0 --- /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 DigitSum(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; +}; 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); + }, + ); +});