Skip to content

Instantly share code, notes, and snippets.

@maxdignan
Created July 11, 2015 16:37
Show Gist options
  • Save maxdignan/dc8b1c51c30f8e799255 to your computer and use it in GitHub Desktop.
Save maxdignan/dc8b1c51c30f8e799255 to your computer and use it in GitHub Desktop.
Test Driven Interview Question CMM
function withFor(list) {
var sum = 0;
list.forEach( function(item) {
if (typeof item === 'number') {
sum += item;
}
});
return sum
};
function withWhile(list) {
var sum = 0;
var iter = 0;
while(list.length > iter) {
if (typeof list[iter] === 'number') {
sum += list[iter];
}
iter++;
}
return sum
}
function withRecursion(list) {
var sum = 0;
if (list.length == 0){
return 0;
}
var num = list.pop();
if (typeof num === 'number') {
sum += num;
}
sum += withRecursion(list);
return sum
}
function callME (func) {
console.log(func([1,2,3,4,5,'hi', undefined, 5]), 'should be 20');
console.log(func([1,2,3,4,5,'hi', undefined]), 'should be 15');
console.log(func([1]), 'should be 1');
console.log(func([]), 'should be 0');
console.log(func([undefined]), 'should be 0');
}
callME(withRecursion);
callME(withWhile);
callME(withFor);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment