Skip to content

Instantly share code, notes, and snippets.

@pmNiko
Last active June 19, 2024 16:53
Show Gist options
  • Save pmNiko/fa5e0644ea7dba95011326e6a756b823 to your computer and use it in GitHub Desktop.
Save pmNiko/fa5e0644ea7dba95011326e6a756b823 to your computer and use it in GitHub Desktop.
Estados del Semaforo

  • 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment