如何解决创建计算器JS
我有一行calc(2).add(3).add(5).res()
,需要写一个解决方案,以便得到10
。
我尝试过了
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())
但是对于我而言,我在2
中而不是在new Calc(2)
中传递了calc(2)
。我该如何更改?
真的很感谢您的帮助!
解决方法
如果我理解正确,这将是一种实现方式:
// GET & POST LOGIN PAGE
app.get('/login',(req,res) => {
res.sendFile(path.join(__dirname,'views','login.html'));
})
app.post('/login',res) => {
const username = req.body.username;
const password = req.body.password;
User.loginUser(username,password,(user) => {
console.log(user);
if (user) {
console.log('Login Success')
res.redirect('/');
} else {
console.log('Login error');
res.sendFile(path.join(__dirname,'loginerror.html'));
}
})
})
,
利用闭包的强大功能,您可以找到一个优雅的解决方案:
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
的初始数字,并通过两种方法返回对象:
-
res()
仅返回数字 -
add()
将使用参数y
,将其与x
相加,然后再次调用calc
,并返回结果。
因此您的界面是完全一致的: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()
。
使用箭头功能可以大大缩短代码:
const calc = x => ({
res: () => x,add: y => calc(x + y)
});
test(
10,actual) {
console.log(
`result is: ${actual}
correct: ${actual === expected}
`)
}
还可以使用相同的模式轻松添加其他操作:
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}
`)
}
请注意,由于每个操作都将立即执行,因此当前唯一的优先权是先行。
,您可以将calc
定义为返回Calc对象的函数。
class Calc{
constructor(num){
this.num = num
}
add(a){
this.num += a;
return this;
}
res() {
return this.num;
}
}
const calc = (input) => new Calc(input);
console.log(calc(2).add(3).add(5).res())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。