Skip to content

Commit a8d1527

Browse files
feat: add spy number algorithm
1 parent 5c39e87 commit a8d1527

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

‎Maths/SpyNumber.js‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @function isSpyNumber
3+
* @description A spy number is a number where the sum of its digits
4+
* equals the product of its digits.
5+
* For example, 1124: 1+1+2+4=8 and 1x1x2x4=8.
6+
* @param {number} n - A positive integer
7+
* @returns {boolean} - True if n is a spy number, false otherwise
8+
* @see https://en.wikipedia.org/wiki/Spy_number
9+
* @example isSpyNumber(1124) => true
10+
* @example isSpyNumber(123) => true
11+
* @example isSpyNumber(1234) => false
12+
*/
13+
const isSpyNumber = (n) => {
14+
if (!Number.isInteger(n) || n < 1) {
15+
throw new TypeError('Input must be a positive integer')
16+
}
17+
const digits = String(n).split('').map(Number)
18+
const sum = digits.reduce((acc, d) => acc + d, 0)
19+
const product = digits.reduce((acc, d) => acc * d, 1)
20+
return sum === product
21+
}
22+
23+
export { isSpyNumber }

‎Maths/test/SpyNumber.test.js‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { isSpyNumber } from '../SpyNumber.js'
2+
3+
describe('isSpyNumber', () => {
4+
test('1 is a spy number (1=1)', () => {
5+
expect(isSpyNumber(1)).toBe(true)
6+
})
7+
8+
test('123 is a spy number (1+2+3=6, 1x2x3=6)', () => {
9+
expect(isSpyNumber(123)).toBe(true)
10+
})
11+
12+
test('1124 is a spy number (1+1+2+4=8, 1x1x2x4=8)', () => {
13+
expect(isSpyNumber(1124)).toBe(true)
14+
})
15+
16+
test('132 is a spy number (1+3+2=6, 1x3x2=6)', () => {
17+
expect(isSpyNumber(132)).toBe(true)
18+
})
19+
20+
test('1234 is NOT a spy number (1+2+3+4=10, 1x2x3x4=24)', () => {
21+
expect(isSpyNumber(1234)).toBe(false)
22+
})
23+
24+
test('22 is NOT a spy number (2+2=4, 2x2=4) wait it is!', () => {
25+
expect(isSpyNumber(22)).toBe(true)
26+
})
27+
28+
test('12 is NOT a spy number (1+2=3, 1x2=2)', () => {
29+
expect(isSpyNumber(12)).toBe(false)
30+
})
31+
32+
test('11 is a spy number (1+1=2, 1x1=1) is false', () => {
33+
expect(isSpyNumber(11)).toBe(false)
34+
})
35+
36+
test('throws TypeError for zero', () => {
37+
expect(() => isSpyNumber(0)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for negative input', () => {
41+
expect(() => isSpyNumber(-123)).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for float input', () => {
45+
expect(() => isSpyNumber(1.5)).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)