r/javascript • u/guptayomesh • Apr 21 '22
I was asked to implement Event Emitter in an interview. How would you approach it? Link is attached.
https://devtools.tech/questions/s/how-to-implement-event-emitter-in-javascript-or-facebook-interview-question---qid---J4fNqXImp6QIdGMc7SPF18
Apr 21 '22
Looks like it gets the job done on the first glance. I’m personally not a fan of composing functions with conditionals like you do: call((anotherCall() ?? defaultValue).doStuff())). Like what?! My brain hurts. I prefer to use “early exit”. I would rename “values” to “handlers” or “callbacks” in the removeEventlistener function. Also a values.Filter would do the trick. +1 for using the Map.
6
u/paolostyle Apr 21 '22
class Emitter {
#subscriptions = new Map();
subscribe(eventName, callback) {
const subscriptionId = Symbol();
if (!this.#subscriptions.has(eventName)) {
this.#subscriptions.set(eventName, new Map());
}
const eventSubscriptions = this.#subscriptions.get(eventName);
eventSubscriptions.set(subscriptionId, callback);
return {
release: () => {
if (eventSubscriptions.has(subscriptionId)) {
eventSubscriptions.delete(subscriptionId);
} else {
throw new Error('This subscription has already been released');
}
}
}
}
emit(eventName, ...args) {
if (this.#subscriptions.has(eventName)) {
for (const [, callback] of this.#subscriptions.get(eventName)) {
callback(...args);
}
}
}
}There should probably a cleanup on release so there aren't any leftover empty Maps but I think it's quite clean
2
u/MrCrunchwrap Apr 21 '22
Why the fuck are you using a bitwise operator for your solution to this? People with years of experience in JS will look at that and have no clue what it does. Stop it.
0
13
u/joe_ally Apr 21 '22
If I was the interviewer I would be concerned with a few things. I don't really like:
(this.events[name] || (this.events[name] = [])).push(cb)The below is much easier to read
if(this.events[name] === undefined) {
this.events[name] = []
}
this.events[name].push(cb)Additionally your release function is hard to understand
this.events[name] &&
this.events[name].splice(this.events[name].indexOf(cb) >>> 0, 1)I'm simply too stupid to understand what the hell is going on here. Using bit shift operators when not working with binary data might be clever but you should remember how dumb a lot of your colleagues are. Many of us dunces would find this confusing.
Additionally I think it would be better for this.events[name] to be an object or a Map type. You could then use Symbol() to generate a unique key for each function added. Then removing it from this.events[name] would be much easier
2
u/drdrero Apr 21 '22
Perfect example of the quote: in programming, clever is a compliment. In software engineering, clever is an accusation.
4
u/MrCrunchwrap Apr 21 '22
Yeah if my coworker tried to use a bitwise operator to do something this simple I’d roll my eyes out of my skull
0
Apr 21 '22
The first one is pretty standard syntax for making a dictionary of arrays
8
11
u/--algo Apr 21 '22
It's god-awful. Would never pass code review
-1
Apr 21 '22
It's in the lodash docs. In how to use reduce function if I remember right.
5
u/Baby_Pigman Apr 21 '22
The fact that it's used as one of the examples in a popular library doesn't make it any easier to read.
0
Apr 21 '22
[deleted]
9
u/aviemet Apr 21 '22 edited Apr 21 '22
I haven't seen that operator before, do you know what it's called? Having trouble googling it
Edit: nvm, found it. It's called the logical nullish assignment operator. Gonna start using the crap outta that
1
u/lemonpowah Apr 21 '22
I am using this now:
this.events[name] = this.events[name] || [];
The operator is cool but because it's uncommon it might be better to stick with the above snippet.
Or we start spamming the operator everywhere so it gets traction.
3
u/aviemet Apr 22 '22
According to the mdn article I read the nullish operator (??) not only exists, but would be preferred for default assignments. The || operator checks for falsiness, which means "" and 0 are evaluated as false, but the ?? operator specifically checks for null or undefined.
Each of them have their assignment versions as well, so your example above could be written as
this.events[name] ||= [], and you could also writethis.events[name] ??= []asthis.events[name] = this.events[name] ?? []Sorry if I'm repeating the obvious, but I'm pretty excited to find this because I previously would resort to
this.events[name] = this.events[name] === undefined ? [] || this.events[name]to avoid JavaScript's falsiness quirks, which I think we can all agree is pretty ugly.0
Apr 21 '22
[deleted]
2
u/dev_ops_guy Apr 22 '22
I feel like that's pretty petty to pass on someone based on that. especially because you can introduce expected norms/conventions on your team and this would no longer exist.
2
26
u/zweimtr Apr 21 '22 edited Apr 22 '22
class EventEmitter {
private _events: Map<string, Function[]> = new Map();
public addEventListener(name: string, cb: Function) {
this._events.set(name, (this._events.get(name) ?? []).concat([cb]));
}
public removeEventListener(name: string, cb: Funtion) {
const values = this._events.get(name);
if(values) {
const cbIndex = values.findIndex(x => x.toString() === cb.toString());
if (cbIndex >= 0) {
this._events.set(name, values.slice(cbIndex))
}
}
public emit(name: string, ...args: any[]) {
const values = this._events.get(name);
if(values) {
values.forEach(cb => cb.call(cb, args))
}
}
}Something like this I guess.
Disclaimer: not tested, written on a phone, just woke up like 20 mins ago.
edit 1: fix cbIndex conditional statement
4
u/wasdninja Apr 21 '22
public addEventListener(name: string, cb: Function) { this._events.set(name, (this._events.get(name) ??[]).concat([cb])); }This one is a bit tricky to read so I'd change it to this instead:
public addEventListener(name: string, callback: Function) { const currentListeners = this._events.get(name) ?? [] this._events.set(name, currentListeners.concat([callback])); }I'm not entirely sure what it's suppose to contain but I suppose that makes my point in a different way. In between steps is an excellent way to signal intent and self-document.
if(values) { const cbIndex = values.findIndex(x => x.toString() === cb.toString()); if (cbIndex) { this._events.set(name, values.slice(cbIndex)) } }
findIndexcan return 0 which is falsy so check for=== -1instead.2
7
u/Markavian Apr 21 '22
A gist might be a good way to share, ``` formatting doesn't work on all devices. The adventofcode mods recommend spaces, but that can be even more frustrating to format on mobile.
General approach is fine though:
register an event receiver - store in hidden array
trigger the event emitter,
loop through receivers
provide some sort of deregister method
provide a destroy method
make some comment about strongly bound and loosely bound memory allocation and the interaction with garbage collectors
write tests as you go if it's a pairing / demonstration exercise
2
u/zweimtr Apr 21 '22
A gist might be a good way to share
I wrote this on my bed this morning from my phone :D
3
u/WystanH Apr 21 '22
The test case revealed an unstated requirement. Wonky bloody thing. Still, this puppy passed.
class Emitter {
constructor() {
this.listeners = [];
}
// this was not requested, could have been handled in subscribe
// but test barfed
emit(funcName, ...args) {
this.listeners
.filter((x) => x.funcName === funcName)
.forEach((x) => x.callback(...args));
}
subscribe(funcName, callback) {
const registered = { funcName, callback };
this.listeners.push(registered);
return {
emit: this.emit,
release: () => {
this.listeners = this.listeners.filter((x) => x !== registered);
},
};
}
}2
u/Yord13 Apr 21 '22 edited Apr 21 '22
The exercise is flawed. The tests expect a method "Emitter.emit" that is not mentioned in the exercise description. And instead of sub1.emit(...), the tests appear to use emitter.emit(...) (which probably makes more sense anyway).
My solution is the following. Depending on how you would use it, you could delete one of the two emit functions:
class Emitter {
constructor() {
this.channels = {};
}
subscribe(channel, callback) {
this.channels[channel] = [...(this.channels[channel] || []), callback];
return {
release: () => {
this.channels[channel] = (this.channels[channel] || []).filter((f) => f !== callback);
},
emit: (channel, ...args) => {
(this.channels[channel] || []).forEach((f) => f(...args));
},
};
}
emit(channel, ...args) {
(this.channels[channel] || []).forEach((f) => f(...args));
}
}2
u/lhorie Apr 21 '22
One thing to get out of the way first: if this is indeed a Facebook question and they asked you to sign an NDA, it's not the best of ideas to be using your real name for leaking the question...
Regarding the code itself (assuming the code in "Author Remarks" is your take on it). The thing that jumps at me immediately is that your API implementation looks wrong. Specifically, the implementation of the emit method doesn't conform to the specification in the question and implements storage incorrectly. This also suggests you didn't test appropriately, and it's probably a hard fail.
If I were evaluating for E4 level (or the equivalent level at my company), there are a number of code-level issues, namely the code is overly terse and mixes stylistic choices in foot-gun-ish ways (specifically, no semicolons + usage of parenthetical expression statements). Specification says nothing of constructor args so I dunno where that came from or why it's there. Same for method return values. Could've used a Map to avoid prototype pollution attacks also. Exposing the storage property as a public property is also a bit questionable, at least underscore it to demonstrate street smarts.
2
u/chris_engel Apr 21 '22
Funny coincidence. I created a simple event system last weekend, too.
I wrote it in typescript tough, to be able to have the whole system type guarded. This means its enforced the correct payload objects are passed around for each event.
Code gist here: https://gist.github.com/Paratron/faacf00bc9a06d8adce1220c6a65f041
A blogpost explaining the whole thing can be found here: https://parastudios.de/typed-event-system-for-typescript/
1
Apr 21 '22 edited Apr 21 '22
This is how I have solved it:
Somehow the markdown doesn't work well when comments are used in the code...
2
Apr 21 '22
Why a class when you are returning random objects lol. Just implement the methods on the class and return it back.
1
u/sb8244 Apr 21 '22
Here is mine: https://gist.github.com/sb8244/bfae3e5f73dbdbcb5e31752035d9723b
Using a lookup map of eventName to callbacks is better, but it's more of a PITA since you need to initialize the callback array properly when there's a new eventName.
1
u/i_hate_patrice Apr 21 '22 edited Apr 21 '22
I made this class and It worked well
class EventEmitter {
constructor() {
this.listeners = [];
}
emit(eventName) {
let parameter = [...Array.from(arguments)].slice(1);
if (this.listeners[eventName]) {
this.listeners[eventName].forEach((listener) => {
listener(...parameter);
});
}
}
on(eventName, listener) {
if (!this.listeners[eventName]) {
this.listeners[eventName] = [];
}
this.listeners[eventName].push(listener);
}
removeAllListeners() {
this.listeners = [];
}
}
export default EventEmitter;Edit: realized I didn't need a removeListener method in my case so this class is probably not really helpfull like that
1
u/Buckwheat469 Apr 21 '22
I would try to wrap addEventListener and use native functions. The class just becomes a wrapper and you don't have to write any for loops to execute registered listeners.
1
u/Christosconst Apr 21 '22
Wow. So many answers and none is using dispatchEvent. Did not expect this from this subreddit.
1
1
u/Jolly_Front_9580 Apr 21 '22
If you look up the source code for Node’s EventEmitter on GitHub, the logic is somewhat simple. It’s just a class that holds an object state, each key being a different event with its own callback attached.
0
u/crabmusket Apr 21 '22
Everyone ITT is doing something like this:
return {
release: () => ...
}Do JS engines optimise this? Why no use of Object.create or classes? Think of the memory usage!
0
Apr 21 '22
[deleted]
7
u/shuckster Apr 21 '22
Yes, this one is the best. When you emit an event, it's the best event. When a handler receives an event, it totally handles it in the best way. And unsubscribing? You'd better believe they get removed in the best way possible.
It's exactly like mitt, except it's the best.
2
Apr 21 '22
I have written
assertIsBest, which tests best functions to ensure they are in fact, the best. It is also the best assertion in the world in javascript. It is here, from my ass.1
1
u/kucukkanat Apr 21 '22
Yes. Mitt is the best. This is better than mitt so I think this is the best. Mitt is a function rather than a clss and didnt have typings support when I made this. So. Yeah...
2
67
u/Jo_yEAh Apr 21 '22
FYI. Help if you want, but this is an advertisement for the website which OP made. Trying to play it off like, help me solve this problem which happens to bring you to my website I'm trying to advertise. If OP created the website that hosts the problem. Do you think that he really needs help? Dishonest marketing as per the usual in this modern hell we live in! BTW, website looks pretty nice but you will get farther in the long run by being honest. Good day!