0

I'd like to create an API somewhat along the lines of this:

const myAPI = {
  sendMessage: (message) => {
    websocket.send(message)
  }
  subscribe: (subject) => {
    websocket.subscribe(subject)
  }
}

I'd like to have an initialization function that makes the websocket object available somehow, like so:

const myAPI = {
  sendMessage: (message) => {
    if (!initialized) { initWebsocket() }
    websocket.send(message)
  }
  subscribe: (subject) => {
    if (!initialized) { initWebsocket() }
    websocket.subscribe(subject)
  }
}

but, I don't know how to share the websocket object across the API functions, and I'd like to avoid duplicating the if statement in every single function.

I was thinking using something like higher-order functions might help, but I'm not sure exactly what I need to use to approach this problem.

Marcelo
  • 157
  • 9

0 Answers0