I’m solving the following kata: Write a program that takes as its first argument one of the words ‘sum,’ ‘product,’ ‘mean,’ or ‘sqrt’ and for further arguments a series of numbers. The program applies the appropriate function to the series.
I have solved it (code below) but it is bulky and inefficient. I’m looking to re-write it have a single function calculator that calls the other functions (i.e. function sum, function product).
My question: how do I write the functions sum, product, sqrt, etc so when called by the function calculator, they properly take the arguments of calculator and compute the math.
Below is the bulky code:
function calculator() {
var sumTotal = 0;
var productTotal = 1;
var meanTotal = 0;
var sqrt;
if(arguments[0] === "sum") {
for(i = 1; i < arguments.length; i++) {
sumTotal += arguments[i];
}
return sumTotal;
}
if(arguments[0] === "product") {
for(i = 1; i < arguments.length; i++) {
productTotal *= arguments[i];
}
return productTotal;
}
if(arguments[0] === "mean") {
for(i = 1; i < arguments.length; i++) {
meanTotal += arguments[i];
}
return meanTotal / (arguments.length-1);
}
if(arguments[0] === "sqrt") {
sqrt = Math.sqrt(arguments[1]);
}
return sqrt;
}
calculator("sqrt", 17);
You can just create an object with the functions you need, and then have the calculator function call the correct one.
You can see an example of this in action on jsFiddle.
If you don’t quite understand what I’m doing in my code, I reccomend reading about
callandapplyin Javascript and also about objects in Javascript.