Comment by chrismorgan

Comment by chrismorgan 3 days ago

2 replies

Using the event dispatch mechanism is flat-out bigger, anyway. Here’s the interface of the original script (that is, global pub/sub functions taking a name), except that the receiver site no longer needs to look at the .detail property so it’s better:

  let t={};
  sub=(e,c)=>((e=t[e]??=new Set).add(c),()=>e.delete(c));
  pub=(n,d)=>t[n]?.forEach(f=>f(d))
The original was 149 bytes; this is 97.

(The nullish coalescing assignment operator ??= has been supported across the board for 4½ years. Avoiding it will cost six more bytes.)

ftigis 3 days ago

This isn't the same though. With EventTarget, if one of the callback throws, the later callbacks would still get called. With yours the later callbacks don't get called.

  • chrismorgan 3 days ago

    True, I forgot about that. Habit of working in Rust, perhaps, and generally avoiding exceptions when working in JavaScript.

    Well then, a few alternatives to replace f=>f(d), each with slightly different semantics:

    • async f=>f(d) (+6, 103 bytes).

    • f=>{try{f(d)}catch{}} (+14, 111 bytes).

    • f=>setTimeout(()=>f(d)) (+16 bytes, 113 bytes).

    • f=>queueMicrotask(()=>f(d)) (+20 bytes, 117 bytes).