Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cache map.get() for size wins #100

Merged
merged 2 commits into from
May 27, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,22 @@ export interface Emitter {
* @name mitt
* @returns {Mitt}
*/
export default function mitt(all: EventHandlerMap): Emitter {
export default function mitt(all?: EventHandlerMap): Emitter {
all = all || new Map();

return {
/**
* Register an event handler for the given type.
*
* @param {string|symbol} type Type of event to listen for, or `"*"` for all events
* @param {Function} handler Function to call in response to given event
* @memberOf mitt
*/
on(type: EventType, handler: Handler) {
const handlers = (all.get(type) || []);
handlers.push(handler);
all.set(type, handlers);
const handlers = all.get(type);
const added = handlers && handlers.push(handler);
if (!added) {
all.set(type, [handler]);
}
},

/**
Expand All @@ -52,8 +53,9 @@ export default function mitt(all: EventHandlerMap): Emitter {
* @memberOf mitt
*/
off(type: EventType, handler: Handler) {
if (all.has(type)) {
all.get(type).splice(all.get(type).indexOf(handler) >>> 0, 1);
const handlers = all.get(type);
if (handlers) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it be better to use Set for the handlers instead?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For speed yes, but Set rejects duplicates. EventEmitter, the API contract mitt adheres to, allows duplicate handlers.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does that mean I can register the same functions twice? That is really interesting.

}
},

Expand Down