Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit96d122f

Browse files
authored
fix: Enhance error handling in factorial function (TheAlgorithms#1430)
1 parent1de5ab7 commit96d122f

File tree

2 files changed

+18
-11
lines changed

2 files changed

+18
-11
lines changed

‎Recursive/Factorial.js

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,14 @@
99
*/
1010

1111
constfactorial=(n)=>{
12-
if(!Number.isInteger(n)){
13-
thrownewRangeError('Not a Whole Number')
14-
}
15-
16-
if(n<0){
17-
thrownewRangeError('Not a Positive Number')
12+
if(!Number.isInteger(n)||n<0){
13+
thrownewRangeError('Input should be a non-negative whole number')
1814
}
1915

2016
if(n===0){
2117
return1
2218
}
19+
2320
returnn*factorial(n-1)
2421
}
2522

‎Recursive/test/Factorial.test.js

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,20 @@ describe('Factorial', () => {
1010
})
1111

1212
it('Throw Error for Invalid Input',()=>{
13-
expect(()=>factorial('-')).toThrow('Not a Whole Number')
14-
expect(()=>factorial(null)).toThrow('Not a Whole Number')
15-
expect(()=>factorial(undefined)).toThrow('Not a Whole Number')
16-
expect(()=>factorial(3.142)).toThrow('Not a Whole Number')
17-
expect(()=>factorial(-1)).toThrow('Not a Positive Number')
13+
expect(()=>factorial('-')).toThrow(
14+
'Input should be a non-negative whole number'
15+
)
16+
expect(()=>factorial(null)).toThrow(
17+
'Input should be a non-negative whole number'
18+
)
19+
expect(()=>factorial(undefined)).toThrow(
20+
'Input should be a non-negative whole number'
21+
)
22+
expect(()=>factorial(3.142)).toThrow(
23+
'Input should be a non-negative whole number'
24+
)
25+
expect(()=>factorial(-1)).toThrow(
26+
'Input should be a non-negative whole number'
27+
)
1828
})
1929
})

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp