-
-
Notifications
You must be signed in to change notification settings - Fork 566
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1557 from wileymab/feature/code-javascript-factorial
Added Factorial in JavaScript
- Loading branch information
Showing
3 changed files
with
57 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,5 +10,6 @@ _site/ | |
*.swp | ||
.pytest_cache/ | ||
__pycache__/ | ||
.scratch | ||
# erlang | ||
*.beam |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
/** | ||
* Calculate the factorial of a given integer input. | ||
* | ||
* @param {Integer} num | ||
*/ | ||
function factorial(num) { | ||
let product = 1; | ||
if ( num > 1 ) { | ||
for ( let i = 2; i <= num; i++ ) { | ||
product *= i | ||
} | ||
} | ||
return product | ||
} | ||
|
||
/** | ||
* Executable function | ||
* | ||
* @param {Command line input} input | ||
*/ | ||
function main(input) { | ||
// Usage text | ||
const usage = 'Usage: please input a non-negative integer'; | ||
|
||
/** | ||
* If we remove all the integer characters from the input and are left with | ||
* an empty string, then we have a valid integer. | ||
*/ | ||
const inputValidation = input.replace(/[0-9]/g,'') | ||
|
||
if ( inputValidation === '' ) { | ||
// Valid integer | ||
const parsedInput = parseInt(input) | ||
if ( parsedInput < 0 ) { | ||
console.log(usage) | ||
} | ||
else if ( parsedInput > 170 ) { | ||
console.log(`Input of ${parsedInput} is too large to calculate a factorial for. Max input is 170.`) | ||
} | ||
else { | ||
console.log(factorial(parsedInput)) | ||
} | ||
} | ||
else { | ||
// Anything non integer | ||
console.log(usage) | ||
} | ||
|
||
} | ||
|
||
// Run the executable function | ||
const input = process.argv[2] | ||
main(input) |