javascript - 编写计算器函数 - 以最实用的编程方式(javascript)

标签 javascript functional-programming

我正在尝试 codewars 中的一个任务,并想用 javascript 函数式编程方式编写。我对我的功能以及如何以更好的方式编写代码有一些疑问。

任务本身是构建一个计算器函数。它将接受以下格式的输入:

'..... + ...'

计算器必须用表示运算的中间字符分割字符串,然后剩下的两个字符串将是两个值。在上面的示例中,第一个值为 5,第二个值为 3。完成此操作后,根据运算符执行操作 - 加法、乘法等。

这是我的代码:

function dotCalculator(equation) {

    function returnSymbol(input) {

        if (input.includes(' + ')) {
            return ' + ';
        } else if (input.includes(' - ')) {
            return ' - ';
        } else if (input.includes(' * ')) {
            return ' * ';
        } else if (input.includes(' / ')) {
            return ' / ';
        }

    }

    let symbolOf = returnSymbol;

    let result = equation.split(symbolOf(equation)).map(x => x.length);
    
    // Array.prototype.add = function(){
    //     return this[0] + this[1];
    // }
}

我知道我的代码还没有完成。我试图理解如何在牢记函数式编程思维方式的情况下正确完成它。也许原型(prototype)继承有点矫枉过正。我正在寻找任何愿意伸出援手的人的一些想法。我尝试编写一个更复杂的reduce之后

let arrMine = equation.split(symbolOf(equation)).map((x) => x.length);

但是看起来太乱了。任何帮助将不胜感激。

最佳答案

我是一个非常函数式编程的菜鸟,这里的管道函数可能有点无缘无故,我可能过于字面地理解了 ..... + ... 示例,但是这是一个尝试:

const arith = {
  '+': (a, b) => a + b,
  '-': (a, b) => a - b,
  '*': (a, b) => a * b,
  '/': (a, b) => a / b,
};

const pipe = (...fns) => (arg) => fns.reduce((res, fn) => fn(res), arg);

const get_input_elements = (input) => input.split(' ');

const get_number = (dots) => dots.length;

const get_numbers = ([str_a, op, str_b]) =>
  [get_number(str_a), op, get_number(str_b)];

const apply_arith = ([a, op, b]) => arith[op](a, b);

const calc = pipe(
  get_input_elements,
  get_numbers,
  apply_arith
);

console.log(calc('..... + ...'));
console.log(calc('..... - ...'));
console.log(calc('...... / ..'));

关于javascript - 编写计算器函数 - 以最实用的编程方式(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71568783/

相关文章:

javascript - 如何使用 javascript 或 jquery 从选择框选项的第一个选项中清空值?

javascript - 使用 webpack-stream & gulp 不会转译 ES6 导入

javascript - 使用 JS 获取 Html 元素背景颜色

functional-programming - 如何以功能方式实现 'state-driven' 程序?

R:它能走多远? (加上通风)

javascript - bool 'not' 函数的函数组合(不是 bool 值)

javascript - 在 iframe 内的隐藏提交按钮上使用 click() 在 FF 和 Chrome 中有效,但在 IE 和 Opera 中无效

javascript - react native 异步存储不保存并且没有错误

C++函数式编程代码片段

haskell - Haskell 中的函数