我正在尝试 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/