The smallest PubSub library possible. Zero Dependencies. 99 bytes.
I wrote this article a while back. But I realized...why not just publish the code?
Smaller than the competition.
Built with JS13K games in mind. Such as cred which is unfortunately in need of some weight loss soon, as it is almost 25KB now.
If you have any ideas that may trim off even one single byte please share it. Create an issue! I don't mind.
This is the entire source (index.js).
let t = {};
sub = (e, c) => ((t[e] ??= new Set()).add(c), (_) => t[e].delete(c));
pub = (e, d) => t[e]?.forEach((f) => f(d));npm install pico-pubsubconst unsub = sub('jump', function (anything) {
console.log("someone jumped - " + anything)
});
pub('jump', "a_user_id")
>> "someone jumped - a_user_id"
unsub()
pub('jump', "another_user_id")
>> Nothing happens now- Might add TS support in the future. For now you can use the following snippet.
declare global {
function pub(event: string, data: any): VoidFunction;
function sub(event: string, callback: (data: any) => void): void;
}The following command will produce a 99b file:
npx esbuild index.js --bundle --minify --format=esm --outfile=bundle.js
nano-pubsub which slims down to an impressive 194b...Not bad at all! But we are looking for the absolute minimal implementation.
/**
* @public
*/
export interface Subscriber<Event> {
(event: Event): void;
}
/**
* @public
*/
export interface PubSub<Message> {
publish: (message: Message) => void;
subscribe: (subscriber: Subscriber<Message>) => () => void;
}
/**
* @public
*/
export default function createPubSub<Message = void>(): PubSub<Message> {
const subscribers: { [id: string]: Subscriber<Message> } =
Object.create(null);
let nextId = 0;
function subscribe(subscriber: Subscriber<Message>) {
const id = nextId++;
subscribers[id] = subscriber;
return function unsubscribe() {
delete subscribers[id];
};
}
function publish(event: Message) {
for (const id in subscribers) {
subscribers[id](event);
}
}
return {
publish,
subscribe,
};
}nanoevents which compresses down to 231b.
They advertise it as 107 bytes but they are including brotli compression which occurs during transfer. Also I am seeing 146b after brotli on my end. Not sure how they are calculating that.
export let createNanoEvents = () => ({
emit(event, ...args) {
for (
let callbacks = this.events[event] || [],
i = 0,
length = callbacks.length;
i < length;
i++
) {
callbacks[i](...args);
}
},
events: {},
on(event, cb) {
(this.events[event] ||= []).push(cb);
return () => {
this.events[event] = this.events[event]?.filter((i) => cb !== i);
};
},
});tiny-pubsub which brings a non critical function to the table as well as an extra function with the way it handles unsubscribing! The agony! This comes in at a whopping 401b, more than 4 times pico-pubsub!
let subscriptions = Object.create(null);
function subscribe(evt, func) {
if (typeof func !== "function") {
throw "Subscribers must be functions";
}
const oldSubscriptions = subscriptions[evt] || [];
oldSubscriptions.push(func);
subscriptions[evt] = oldSubscriptions;
}
function publish(evt) {
let args = Array.prototype.slice.call(arguments, 1);
const subFunctions = subscriptions[evt] || [];
for (let i = 0; i < subFunctions.length; i++) {
subFunctions[i].apply(null, args);
}
}
function unsubscribe(evt, func) {
const oldSubscriptions = subscriptions[evt] || [];
const newSubscriptions = oldSubscriptions.filter((item) => item !== func);
subscriptions[evt] = newSubscriptions;
}
function cancel(evt) {
delete subscriptions[evt];
}
module.exports = { subscribe, publish, unsubscribe, cancel };This library adds pub and sub to the global namespace.