Skip to content

Commit

Permalink
cache map.get() for size wins (#100)
Browse files Browse the repository at this point in the history
* cache map.get() for size wins

* Further reduce size of on()
  • Loading branch information
developit authored May 27, 2020
1 parent 8d987a7 commit 3bce9a1
Showing 1 changed file with 9 additions and 7 deletions.
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);
}
},

Expand Down

0 comments on commit 3bce9a1

Please sign in to comment.