// index.js
const app = getApp();
const {REGEXP} = app;
Page({
data:{
express:"",
result:"",
isEqualBtnClicked:false
},
reset:function(e){
this.setData({
express:"",
result:"",
isEqualBtnClicked:false
})
},
preProcess:function(express){
if(REGEXP.test(express[express.length-1])){
express = express.slice(0,express.length-1);
}
return express;
},
delete:function(){
const {express} = this.data;
let newExpress = express.slice(0,express.length-1);
let expressForCalc = this.preProcess(newExpress);
let temp = this.calculate(expressForCalc);
let newResult = temp==="0"?"":temp;
this.setData({
express:newExpress,
result:newResult
})
},
equal:function(){
const {express} = this.data;
let expressForCalc = this.preProcess(express);
this.setData({
result:"",
express:this.calculate(expressForCalc),
isEqualBtnClicked:true
})
},
clickNumBtn:function(e){
const val = e.target.dataset.val;
let {express} = this.data;
express+=val;
this.setData({
express:express,
result:this.calculate(express)
},function(){
console.log(`click numBtn,current express: ${this.data.express},ittime to get result:${this.calculate(express)}`);
})
},
clickOptBtn:function(e){
let {express} = this.data;
if(express==="" || REGEXP.test(express[express.length-1])) return;
const opt = e.target.dataset.val;
express+=opt;
this.setData({
express:express
},function(){
console.log("click optBtn,current express:",this.data.express);
})
},
getLeftAndRight:function(express,i){
const REGEXP = /\d+(\.\d+)?/;
const REGEXP2 = /[\+\-×÷]/;
let front = express.slice(0,i);
let back = express.slice(i+1);
let temp = front.split(REGEXP2);
let left = Number(temp[temp.length-1]);
let right = Number(back.match(REGEXP)[0]);
return {left,right};
},
calculate:function(express){
const REGEXP1 = /[×÷]/;
const REGEXP2 = /\+(\d+)(\.\d+)?/;//正数
const REGEXP3 = /\-(\d+)(\.\d+)?/;//负数
const REGEXP4 = /\d+(\.\d+)?/;
const {getLeftAndRight} = this;
let temp;
let result = 0;
//先乘除
while((temp = express.match(REGEXP1)) !== null){
let opt = temp[0];
let i = temp["index"];
let {left,right} = getLeftAndRight(express,i);
switch(opt){
case "×":express = express.replace(left+opt+right,left*right);break;
case "÷":express = express.replace(left+opt+right,left/right);break;
}
}
//后加减
let firstNum = 0,sum1=0,sum2=0;
let res = express.match(REGEXP4);
if(res!==null && res["index"]===0){
let str = res[0];
firstNum = Number(str);
express = express.slice(str.length);
}
while((temp = express.match(REGEXP2)) != null){
let str = temp[0];
express = express.replace(str,"");
sum1 += Number(str.slice(1));
}
while((temp = express.match(REGEXP3)) != null){
let str = temp[0];
express = express.replace(str,"");
sum2 += Number(str.slice(1));
}
result += firstNum + sum1 - sum2;
return result.toString();
}
})
暂时没有评论,来抢沙发吧~