// 仿LISP运算
function add(a, b) {
if (a == "error" || b == "error") {
return "error";
} else {
return Number(a) + Number(b);
}
}
function sub(a, b) {
if (a == "error" || b == "error") {
return "error";
} else {
return Number(a) - Number(b);
}
}
function mul(a, b) {
if (a == "error" || b == "error") {
return "error";
} else {
return Number(a) * Number(b);
}
}
function div(a, b) {
if (a == "error" || b == "error" || b == "0") {
return "error";
} else {
return Math.floor(Number(a) / Number(b));
}
}
function lisp(str) { // 封装上面四则运算,通过eval执行计算结果
let tmp=str.replace(/\((sub|div|mul|add) /g,'$1(').replace(/ /g,',');
console.log(eval(tmp))
}
lisp('(sub (mul 2 4) (div 9 3))')
仿LISP运算
最新推荐文章于 2024-06-25 14:29:23 发布