Skip to content

Commit 5a69a9c

Browse files
feat: add digit product algorithm
1 parent 5c39e87 commit 5a69a9c

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

‎Maths/DigitProduct.js‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @function digitProduct
3+
* @description Calculates the product of all digits of a given integer.
4+
* @param {number} n - A non-negative integer
5+
* @returns {number} - The product of all digits
6+
* @see https://en.wikipedia.org/wiki/Multiplicative_digital_root
7+
* @example digitProduct(123) => 6
8+
* @example digitProduct(999) => 729
9+
* @example digitProduct(0) => 0
10+
*/
11+
const digitProduct = (n) => {
12+
if (!Number.isInteger(n) || n < 0) {
13+
throw new TypeError('Input must be a non-negative integer')
14+
}
15+
return String(n)
16+
.split('')
17+
.reduce((product, d) => product * Number(d), 1)
18+
}
19+
20+
export { digitProduct }

‎Maths/test/DigitProduct.test.js‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { digitProduct } from '../DigitProduct.js'
2+
3+
describe('digitProduct', () => {
4+
test('digitProduct(0) returns 0', () => {
5+
expect(digitProduct(0)).toBe(0)
6+
})
7+
8+
test('digitProduct(1) returns 1', () => {
9+
expect(digitProduct(1)).toBe(1)
10+
})
11+
12+
test('digitProduct(123) returns 6', () => {
13+
expect(digitProduct(123)).toBe(6)
14+
})
15+
16+
test('digitProduct(999) returns 729', () => {
17+
expect(digitProduct(999)).toBe(729)
18+
})
19+
20+
test('digitProduct(111) returns 1', () => {
21+
expect(digitProduct(111)).toBe(1)
22+
})
23+
24+
test('digitProduct(100) returns 0', () => {
25+
expect(digitProduct(100)).toBe(0)
26+
})
27+
28+
test('digitProduct(99) returns 81', () => {
29+
expect(digitProduct(99)).toBe(81)
30+
})
31+
32+
test('digitProduct(555) returns 125', () => {
33+
expect(digitProduct(555)).toBe(125)
34+
})
35+
36+
test('throws TypeError for negative input', () => {
37+
expect(() => digitProduct(-123)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for float input', () => {
41+
expect(() => digitProduct(1.5)).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for string input', () => {
45+
expect(() => digitProduct('123')).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)