Skip to content

Commit

Permalink
Merge pull request #1557 from wileymab/feature/code-javascript-factorial
Browse files Browse the repository at this point in the history
Added Factorial in JavaScript
  • Loading branch information
jrg94 authored Oct 10, 2019
2 parents 65552e6 + d5b3cc8 commit a02a70c
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ _site/
*.swp
.pytest_cache/
__pycache__/
.scratch
# erlang
*.beam
4 changes: 3 additions & 1 deletion archive/j/javascript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Welcome to Sample Programs in JavaScript!
- [Fizz Buzz in JavaScript][4]
- [Baklava in JavaScript][8]
- Solution borrowed from @toturkmen via the [baklava repo][1]
- [Factorial in JavaScript][15]
- [Fibonacci in JavaScript][9]
- [Capitalize in JavaScript][12]
- [Import in JavaScript][13]
Expand Down Expand Up @@ -41,4 +42,5 @@ Welcome to Sample Programs in JavaScript!
[11]: https://www.w3schools.com/js/
[12]: https://github.com/TheRenegadeCoder/sample-programs/issues/1067
[13]: https://github.com/TheRenegadeCoder/sample-programs/issues/1178
[14]: https://github.com/TheRenegadeCoder/sample-programs/issues/1191
[14]: https://github.com/TheRenegadeCoder/sample-programs/issues/1191
[15]: https://github.com/TheRenegadeCoder/sample-programs/issues/1383
53 changes: 53 additions & 0 deletions archive/j/javascript/factorial.js
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)

0 comments on commit a02a70c

Please sign in to comment.