大体思路:电梯信号分为外部信号和内部信号,区别为:外部信号有方向信息,内部信号没有,所以会对所有信号做一个收集。收集完成并处理后,就进行分类,分类思路:可以制定往上楼层数和往下楼层数二个目标队列,往上的一个,往下的一个,然后定时从该二个队列中取楼层数,其中还会有方向的判断,具体代码如下:
downDests=[],
index=0,
direction=0,
current=1,
top=20,
bottom=-4,
insideSignals=[],
outsideSignals=[];
function addDest(sg){
if (typeof sg === "object") {
if(sg.d===1 && indexOf(upDests,sg.n)===-1){
upDests.push(sg.n);
upDests.sort(function(a,b){return a>b});
}
if(sg.d===-1 && indexOf(downDests,sg.n)===-1){
downDests.push(sg.n);
downDests.sort(function(a,b){return a<b});
}
}else if (!isNaN(sg)) {
if(sg>current){
if(indexOf(upDests,sg)===-1){
upDests.push(sg);
upDests.sort(function(a,b){return a>b});
}
}else if(sg<current){
if(indexOf(downDests,sg)===-1){
downDests.push(sg);
downDests.sort(function(a,b){return a<b});
}
}
}
if(upDests.length===1 && downDests.length === 0 && direction === 0){
direction=1;
}
if(upDests.length===0 && downDests.length === 1 && direction === 0){
direction=-1;
}
}
function indexOf(arr,el){
var i=arr.length,
ret=-1;
while(i--){
if(arr[i]===el){
ret=i;
break;
}
}
return ret;
}
function updateDest(dests){
var dest;
if (dests.length) {
dest = dests[0];
if (current === dest) {
dests.splice(0, 1);
}else {
current += direction;
}
}
return dests.length;
}
function refresh(){
var dest,
d;
if (direction === 1) {
updateDest(upDests);
}else if (direction === -1) {
updateDest(downDests);
}
(current===top) || (!upDests.length && downDests.length) && (direction=-1);
(current===bottom) || (upDests.length && !downDests.length) && (direction=1);
!upDests.length && !downDests.length && (direction=0);
direction!==0 && console.log(current);
}
简单测试用例:
addDest(2);
addDest(5);
//外部信号下到3楼
setTimeout(function(){
addDest({
d:-1,
n:3
});
},1500);
//外部信号上到8楼
setTimeout(function(){
addDest({
d:1,
n:8
});
},2000);
//内部信号1楼
setTimeout(function(){
addDest(1);
},2500);
setInterval(refresh,50);