Commit 6eb50899 authored by missingdays's avatar missingdays

Create factorial function and add all tests

parent ace46aba
...@@ -5,8 +5,35 @@ ...@@ -5,8 +5,35 @@
* Distributed under terms of the MIT license. * Distributed under terms of the MIT license.
*/ */
function factorial() { function factorial(n) {
return 1; var e = new Error('Argument should be a positive number')
if(!isNumeric(n)) {
throw e;
}
if(!isInt(n)) {
throw e;
}
if(n < 0) {
throw e;
}
var value = 1;
for(var i = 2; i <= n; i++) {
value *= i;
}
return value;
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isInt(n){
return Number(n)===n && n%1===0;
} }
module.exports = factorial; module.exports = factorial;
...@@ -10,7 +10,49 @@ var my_factorial = require('../src/my_factorial'); ...@@ -10,7 +10,49 @@ var my_factorial = require('../src/my_factorial');
exports.testCalculatesCorrectly = function(test){ exports.testCalculatesCorrectly = function(test){
test.equal(1, my_factorial(0)); test.equal(1, my_factorial(0));
test.equal(1, my_factorial(1));
test.equal(2, my_factorial(2));
test.equal(6, my_factorial(3));
test.equal(120, my_factorial(5));
test.done(); test.done();
} }
exports.testCalculatesCorrectlyForBigNumbers = function(test) {
test.equal(355687428096000, my_factorial(17));
test.equal(620448401733239439360000, my_factorial(24));
test.equal(15511210043330985984000000, my_factorial(25));
test.done();
}
exports.testThrowsWithIncorrectArgument = function(test) {
test.throws(
function() {
my_factorial("10");
},
Error,
"Fail for non-numeric argument"
);
test.throws(
function() {
my_factorial(2.5);
},
Error,
"Fail for float argument"
);
test.throws(
function() {
my_factorial(-3);
},
Error,
"Fail for negative argument"
);
test.done();
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment