Skip to content

Instantly share code, notes, and snippets.

@droid001
Created October 20, 2022 14:18
Show Gist options
  • Save droid001/b053123552b8b698e2c5717a03bde42c to your computer and use it in GitHub Desktop.
Save droid001/b053123552b8b698e2c5717a03bde42c to your computer and use it in GitHub Desktop.
PubSub class with UUID
export const getUUID = ()=>{
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace( /[xy]/g ,
function(c) {
var rnd = Math.random()*16 |0, v = c === 'x' ? rnd : (rnd&0x3|0x8) ;
return v.toString(16);
}
);
}
export default class PubSub {
#topics = {};
constructor(...args) {
super(...args);
}
subscribe(topic, func) {
if (!this.#topics[topic]) {
this.#topics[topic] = [];
}
const token = getUUID();
this.#topics[topic].push({
token,
func,
});
return token;
}
unsubscribe(token) {
for (const m in this.#topics) {
if (this.#topics[m]) {
for (let i = 0, j = this.#topics[m].length; i < j; i++) {
if (this.#topics[m][i].token === token) {
this.#topics[m].splice(i, 1);
return token;
}
}
}
}
return this;
}
publish(topic, args) {
if (!this.#topics[topic]) {
return false;
}
const subscribers = this.#topics[topic];
let len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
return this;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment