aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJason Miller <[email protected]>2020-05-27 12:32:57 -0400
committerGitHub <[email protected]>2020-05-27 12:32:57 -0400
commit3bce9a164db0340cf1cc1b355274f6d419499528 (patch)
tree53021f817b1411f99b6f776a2c2607e5e1732573
parent8d987a71f2d6f4fdaec65752e036b4fd54604933 (diff)
cache map.get() for size wins (#100)
* cache map.get() for size wins * Further reduce size of on()
-rw-r--r--src/index.ts16
1 files changed, 9 insertions, 7 deletions
diff --git a/src/index.ts b/src/index.ts
index f0a2ebb..e1503e2 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -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]);
+ }
},
/**
@@ -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);
}
},