// Function executed only once
const callOnce = (fn)=> (...args)=> {
if (fn)
fn(...args)
fn = null
}
const wrap = (port) => {
const obj = {}
obj.postMessage = (message, reply)=> {
port.postMessage({message, reply})
}
port.onmessage = ({message, reply})=> {
if(obj.onmessage)
obj.onmessage(message, callOnce(reply))
}
return obj
}
class BetterChannel {
constructor() {
const {port1, port2} = new SomeChannel()
this.port1 = wrap(port1)
this.port2 = wrap(port2)
}
}
Create a new object that encapsulates the functionalities of an existing 'SomeChannel.' Pass both messages and replies in the 'postMessage' method. Call the 'onMessage' function with the received message and reply.