From 7eb2efca397fb348e5cee8d95d39aee430b52922 Mon Sep 17 00:00:00 2001 From: James Israel Date: Wed, 4 Oct 2023 11:44:20 +0100 Subject: [PATCH] fix: Enhance error handling in factorial function. Refactored the factorial function to improve error handling. Now, a single check verifies if the input is a non-negative whole number, throwing a RangeError with the message 'Input should be a non-negative whole number' for invalid inputs.This simplification enhances code readability and maintains the desired behavior. --- Recursive/Factorial.js | 9 +++------ Recursive/test/Factorial.test.js | 20 +++++++++++++++----- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/Recursive/Factorial.js b/Recursive/Factorial.js index 5a0d560514..4e2b3c1bff 100644 --- a/Recursive/Factorial.js +++ b/Recursive/Factorial.js @@ -9,17 +9,14 @@ */ const factorial = (n) => { - if (!Number.isInteger(n)) { - throw new RangeError('Not a Whole Number') - } - - if (n < 0) { - throw new RangeError('Not a Positive Number') + if (!Number.isInteger(n) || n < 0) { + throw new RangeError('Input should be a non-negative whole number') } if (n === 0) { return 1 } + return n * factorial(n - 1) } diff --git a/Recursive/test/Factorial.test.js b/Recursive/test/Factorial.test.js index 5f32a44332..e89be9831e 100644 --- a/Recursive/test/Factorial.test.js +++ b/Recursive/test/Factorial.test.js @@ -10,10 +10,20 @@ describe('Factorial', () => { }) it('Throw Error for Invalid Input', () => { - expect(() => factorial('-')).toThrow('Not a Whole Number') - expect(() => factorial(null)).toThrow('Not a Whole Number') - expect(() => factorial(undefined)).toThrow('Not a Whole Number') - expect(() => factorial(3.142)).toThrow('Not a Whole Number') - expect(() => factorial(-1)).toThrow('Not a Positive Number') + expect(() => factorial('-')).toThrow( + 'Input should be a non-negative whole number' + ) + expect(() => factorial(null)).toThrow( + 'Input should be a non-negative whole number' + ) + expect(() => factorial(undefined)).toThrow( + 'Input should be a non-negative whole number' + ) + expect(() => factorial(3.142)).toThrow( + 'Input should be a non-negative whole number' + ) + expect(() => factorial(-1)).toThrow( + 'Input should be a non-negative whole number' + ) }) })