创建计算器(JS) [英] Create calculator (JS)
问题描述
我有一行 calc(2).add(3).add(5).res()
,需要写一个解决方案,以便我有 10
因此.我尝试过了
I have a line calc(2).add(3).add(5).res()
and need to write a solution so that I have 10
as a result.
I tried this
class Calc{
constructor(num){
this.num = num
}
add(a){
this.num += a;
return this;
}
res() {
return this.num;
}
}
let calc = new Calc(2)
console.log(calc.add(3).add(5).res())
但是在我的情况下,我在 new Calc(2)
中传递了 2
,而不是在 calc(2)
中传递了.我该如何更改?
but in my case I pass 2
in new Calc(2)
, not in calc(2)
. How can I change it?
将非常感谢您的帮助!
推荐答案
利用闭包的强大功能,您可以得到一个优雅的解决方案:
You can have an elegant solution leveraging the power of closures:
function calc(x) {
return {
res: function() {
return x;
},
add: function(y) {
return calc(x + y)
}
}
}
test(
10,
calc(10).res()
);
test(
10,
calc(3).add(7).res()
);
test(
10,
calc(8).add(2).res()
);
test(
10,
calc(2).add(3).add(5).res()
);
function test(expected, actual) {
console.log(
`result is: ${actual}
correct: ${actual === expected}
`)
}
calc
函数采用称为 x
的初始数字,并使用两种方法返回对象:
The calc
function takes the initial number called x
and returns an object with two methods:
-
res()
仅返回数字 -
add()
将采用参数y
,将其与x
相加,然后再次使用calc
结果.
res()
just returns the numberadd()
will take a parametery
, sums it withx
and callscalc
again with the result.
因此您的界面是完全一致的: calc(10)
将与 calc(3).add(7)
或 calc(8).add(2)
或 calc(2).add(3).add(5)
.您可以根据需要随意链接 add
调用,并且始终保持相同.调用 res()
将结束链,只给您 calc
当前持有的号码-是否已完成 calc(10).res()
或 calc(2).add(3).add(5).res()
.
So your interface is entirely consistent: calc(10)
is going to be the same as calc(3).add(7)
or calc(8).add(2)
or calc(2).add(3).add(5)
. You can chain the add
calls as much as you want and it's always going to be the same. Calling res()
will end the chain and just give you the number that calc
currently holds - whether you've done calc(10).res()
or calc(2).add(3).add(5).res()
.
使用箭头功能可以大大缩短代码:
The code can be shortened a lot using arrow functions:
const calc = x => ({
res: () => x,
add: y => calc(x + y)
});
test(
10,
calc(10).res()
);
test(
10,
calc(3).add(7).res()
);
test(
10,
calc(8).add(2).res()
);
test(
10,
calc(2).add(3).add(5).res()
);
function test(expected, actual) {
console.log(
`result is: ${actual}
correct: ${actual === expected}
`)
}
还可以使用相同的模式轻松添加其他操作:
Other operations can also easily be added using the same pattern:
const calc = x => ({
res: () => x,
add: y => calc(x + y),
sub: y => calc(x - y),
mul: y => calc(x * y),
div: y => calc(x / y)
});
test(
2,
calc(5).add(5).mul(2).sub(4).div(8).res()
// (((5 + 5) * 2) - 4) / 8 =
// ((10 * 2) - 4) / 8 =
// (20 - 4) / 8 =
// 16 / 8 = 2
);
function test(expected, actual) {
console.log(
`result is: ${actual}
correct: ${actual === expected}
`)
}
请注意,由于每个操作都将立即执行,因此当前唯一的优先级是先到先得.
Note that since each operation is executed immediately, so the only precedence you currently have is what comes first.
这篇关于创建计算器(JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!