DEV Community

artydev
artydev

Posted on

Command Pattern using Generators in Javascript

I have already mentionned Karismir Tsonev in my posts.
Here is an example illustrating his implementation of the command pattern



function *player(maxpong = 10) {
  let i = -1;
  let resp = "pong"
  while (++i < maxpong) {
    resp = yield resp
    document.write(resp + "<br />")
  }
}

function play(gen, tag) {
  let state = gen.next (tag)
  switch (state.value) {
    case "ping" :
     play(gen, "pong")
    break;
    case "pong" :
     play(gen, "ping")
    break; 
    default: 
     console.log("end game")
  } 
}


play(player()) 


Enter fullscreen mode Exit fullscreen mode

You can play with in here : PingPong

and the official example from Krasimir

commander(robot());

function* robot() {
  const catURL = yield ["get-cat"];
  const imgTag = yield ["format", catURL];
  console.log(imgTag);
}
async function commander(gen, passBack) {
  let state = gen.next(passBack);
  switch (state.value ? state.value[0] : null) {
    case "get-cat":
      const res = await fetch("https://api.thecatapi.com/v1/images/search");
      const data = await res.json();
      return commander(gen, data[0].url);
    case "format":
      return commander(gen, `<img src="${state.value[1]}" />`);
  }
  if (!state.done) {
    commander(gen);
  }
}
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)