JavaScript(初级)Kata - 使用函数构建计算器 [英] JavaScript (Beginner-Level) Kata - Building a Calculator Using Functions

查看:114
本文介绍了JavaScript(初级)Kata - 使用函数构建计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决以下问题:编写一个程序,将第一个参数作为sum,product,mean或sqrt之一,并进一步论证一系列数字。该程序将适当的功能应用于该系列。

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).

我的问题:如何编写函数sum,product,sqrt等,所以当函数计算器调用它们时,它们会正确地获取计算器的参数并计算数学。

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.

以下是庞大的代码:

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.

var operations = {
  sum: function() { /* sum function */ },
  product: function() { /* product function */ },
  mean: function() { /* mean function */ },
  sqrt: function() { /* sqrt function */ }
};

function calculator(operation) {
  operation = operations[operation];
  var args = Array.prototype.slice.call(arguments, 1);
  return operation.apply(this, args);
}

你可以在jsFiddle上看到这个实例的一个例子

如果你不太清楚我在代码中做了什么,我会推荐阅读 在Javascript中调用应用 以及 Javascript中的对象

If you don't quite understand what I'm doing in my code, I reccomend reading about call and apply in Javascript and also about objects in Javascript.

这篇关于JavaScript(初级)Kata - 使用函数构建计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆