- Esta es una posible solución al problema del cambio de estado de un semaforo.
- El objetivo es seguir la secuencia
- Rojo -> Amarillo -> Verde -> Amarillo -> Rojo -> ...repite secuancia
El siguiente código se puede correr en cualquier Playground JS
const SemaforoState = ['Rojo', 'Amarillo', 'Verde', 'Amarillo'];
class Semaforo {
private states : Array<string>;
private readonly initialStateKey = 0;
private state = this.initialStateKey;
constructor(states: Array<string>){
this.states = states;
}
public setKeyState(newkeyState: number){
this.state = newkeyState;
}
public next(){
const newKeyState = this.state + 1;
this.states[ newKeyState ]
? this.setKeyState(newKeyState)
: this.setKeyState(this.initialStateKey)
}
public getState(){
return this.states[this.state]
}
}
const semaforo = new Semaforo(SemaforoState);
semaforo.getState()
semaforo.next()
semaforo.getState()
semaforo.next()
semaforo.getState()
semaforo.next()
semaforo.getState()
semaforo.next()
semaforo.getState()