最近公司人多厕所少,写个代码描述下场景,有点恶心,见谅哈哈
//排队上厕所,有点恶心的场景描述,哈哈
//状态 0:在排队 1:处理中 2 上完 3 取消
const WashRoomMap={};
//厕所
class WashRoom {
constructor(name){
this.name=name||'test';
if(!WashRoomMap[name]){
WashRoomMap[name]={
bit:[],
curN:0,
orderMap:{}//待处理的订单
};
}
this.shopOrder=WashRoomMap[this.name];
this.resData={flag:'S'}
this.getN();
}
//获取排队人数
getN(){
//给你一个单号
this.myN=this.shopOrder.bit.length;
this.shopOrder.bit[this.myN]='0';
this.shopOrder.orderMap[this.myN]=this;
}
//排队
wait(overTime){
const n=this.myN-this.shopOrder.curN;
if(n<0){
return {flag:'F'}
}
if(n>0){
return new Promise((res)=> {
this.res=res;
if(overTime){
//超时取消
this.timeInter=setTimeout(()=>{
if(this.res){
this.shopOrder.bit[this.myN]='3';
this.res({
flag:'F',
code:'overtime',
msg:'超时'+overTime+'ms取消订单',
})
this.timeInter=null;
this.res=null;
}
},overTime)
}
})
}else if(n===0){
return this.resData;
}
}
//下一个订单
next(){
if(this.myN===this.shopOrder.curN){
this.shopOrder.curN++
if(this.shopOrder.curN<this.shopOrder.bit.length){
this.shopOrder.orderMap[this.shopOrder.curN].resolve();
delete this.shopOrder.orderMap[this.shopOrder.curN];
}
}
}
//等待完成
resolve(){
if(this.shopOrder.bit[this.myN]==='0'){
this.shopOrder.bit[this.myN]='1';
if(this.timeInter){
clearTimeout(this.timeInter);
this.timeInter=null;
}
if(this.res){
this.res(this.resData)
this.res=null;
}
delete this.shopOrder.orderMap[this.myN];
}else if(this.shopOrder.bit[this.myN]!=='1'){
this.next();
}
}
//结束订单
end(){
if(this.myN>=this.shopOrder.curN){
this.shopOrder.bit[this.myN]='2';
this.next()
}
}
}
module.exports=WashRoom;
输出:
"C:Program Files
odejs
ode.exe" D:360jr360jr-wlhkoa-appsrcwashRoom.js
0 '排队'
1 '排队'
2 '排队'
3 '排队'
4 '排队'
5 '排队'
0 '排队完成'
0 '开始上厕所'
0 '拉屎'
0 '洗手'
0 '结束'
1 '排队完成'
1 '开始上厕所'
1 '拉屎'
1 '洗手'
3 '超时,等不下去了'
4 '超时,等不下去了'
1 '结束'
2 '排队完成'
2 '开始上厕所'
2 '拉屎'
2 '洗手'
2 '结束'
5 '排队完成'
5 '开始上厕所'
5 '拉屎'
5 '洗手'
5 '结束'
Process finished with exit code 0