Skip to content

feat(maths): add DigitSum #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Maths/DigitSum.ts
Original file line number Diff line number Diff line change
@@ -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;
};
19 changes: 19 additions & 0 deletions Maths/test/DigitSum.test.ts
Original file line number Diff line number Diff line change
@@ -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);
},
);
});