I did this code for an interview. Can you tell me how it looks? I didn't get the job, so I'm wondering what I could do better in my code.
/**
* TASK 1: IMPLEMENT: C - binomial coefficient
*
* C(n,k) = n! / [ k! (n - k)! ]
* Where x! is the factorial of x
*
* Use a recursive solution. If needed, you can implement helper functions.
*/
function C(n,k) {
"use strict";
/**
* ~~OMID~~
* The code is not linted, or refactored on purpose.
* Tested with node 0.10.32.
*/
/**
* factorial() returns the factorial
* of any none-negative number.
* @param {integer}
*/
function factorial(number) {
var result = 1;
if(number < 0){
return;
} else if (number <= 1) {
return result;
}
else {
result = number * factorial(number-1);
}
return result;
}
// Testing numerality of parameteres, n and k
if(isNaN(parseFloat(n)) && isFinite(n) && isNaN(parseFloat(n)) && isFinite(n)) {
return;
}
else {
/**
* Implementing the formula.
* C(n,k) = n! / [ k! (n - k)! ]
*/
return (factorial(n)/factorial(k)*factorial(n-k));
}
}
/**
* TASK 2: IMPLEMENT: Tests for function C
*
* Write a set of tests, that validate your binomial coefficient function.
* Write as many test cases as you feel is needed.
*/
(function testBinomialCoefficient() {
var tests = {
example: function() {
var pass = typeof C === "function";
return {
success: pass,
message: (!pass) ? 'Expected C to be a function' : ''
};
},
normalInteger: function() {
var pass = C(5, 4) === 5;
return {
success: pass,
message: (!pass) ? 'C(5,4) Should be equal to 5': ' '
};
},
negativeInput: function() {
var pass = isNaN(C(-5, 4));
return {
success: pass,
message: (!pass) ? 'Negative input must result in NaN': ' '
};
},
smallerSecondParam: function() {
var pass = isNaN(C(10, 19));
return {
success: pass,
message: (!pass) ? 'Second parameter should be smaller': ' '
};
},
};
// ---- You shouldn't change the code below this line ----
for (var test in tests) {
var result = tests[test].apply(undefined);
if (result.success) {
console.log("Passed: " + test);
} else {
console.log("Failed: " + test + ", Message: " + result.message);
}
}
// ---- You shouldn't change the code over this line ----
})();
21!
is already too big to fit in a 64 bit integer. The interviewer should be made aware that his arbitrary requirement makes the solution very far from optimal :) \$\endgroup\$