From 9513bcd77a9eb1ab1090ddb942642e0d438a8b14 Mon Sep 17 00:00:00 2001 From: merelymyself <88221256+merelymyself@users.noreply.github.com> Date: Fri, 22 Apr 2022 00:28:29 +0800 Subject: [PATCH] merge: WhileLoopFactorial: Optimize and add tests (#992) * Optimised the factorial function. There was previously an unnecessary check for if the number was 0 or 1. * Create WhileLoopFactorial.test.js The test was not present previously. * result *= num * Update WhileLoopFactorial.test.js * testFactorial function * Space for formatting. * should fix the formatting issues. I was having trouble with npx standard, so I just used the online verifier at https://standardjs.com/demo.html --- Maths/WhileLoopFactorial.js | 10 ++++------ Maths/test/WhileLoopFactorial.test.js | 12 ++++++++++++ 2 files changed, 16 insertions(+), 6 deletions(-) create mode 100644 Maths/test/WhileLoopFactorial.test.js diff --git a/Maths/WhileLoopFactorial.js b/Maths/WhileLoopFactorial.js index 7e04bbafa..943fabd8d 100644 --- a/Maths/WhileLoopFactorial.js +++ b/Maths/WhileLoopFactorial.js @@ -1,15 +1,13 @@ /* - author: Theepag + author: Theepag, optimised by merelymyself */ export const factorialize = (num) => { - // Step 1. variable result to store num - let result = num - // If num = 0 OR 1, the factorial will return 1 - if (num === 0 || num === 1) { return 1 } + // Step 1. Handles cases where num is 0 or 1, by returning 1. + let result = 1 // Step 2. WHILE loop while (num > 1) { + result *= num // or result = result * num; num-- // decrement 1 at each iteration - result = result * num // or result = result * num; } // Step 3. Return the factorial return result diff --git a/Maths/test/WhileLoopFactorial.test.js b/Maths/test/WhileLoopFactorial.test.js new file mode 100644 index 000000000..6cec49f36 --- /dev/null +++ b/Maths/test/WhileLoopFactorial.test.js @@ -0,0 +1,12 @@ +import { factorialize } from '../WhileLoopFactorial' + +function testFactorial (n, expected) { + test('Testing on ' + n + '!', () => { + expect(factorialize(n)).toBe(expected) + }) +} + +testFactorial(3, 6) +testFactorial(7, 5040) +testFactorial(0, 1) +testFactorial(12, 479001600)