map-ext
TypeScript icon, indicating that this package has built-in type declarations

0.1.5 • Public • Published

A simple addition to (weak) map

Personally I hate it to check if something is in a map, and if not add an object. So, I always write this small snippet, I decided to make a repo out of it.

A simple example;

import {WeakMapExt} from "map-ext";

type EventHandler = (...[]) => any;

const eventStore = new WeakMapExt<object, MapExt<string, Set<EventHandler>>>(() => new MapExt(() => new Set()));

class Events {
    async emit(key: string, ...args: any[]) {
        for (const cb of eventStore.get(this).get(key)) {
            await cb(...args);
        }
    }

    on(key: string, cb: EventHandler) {
        eventStore.get(this).get(key).add(cb);
    }

    off(key: string, cb: EventHandler) {
        eventStore.get(this).get(key).delete(cb);
    }
}

esm - commonjs

Since this package is so small it supports both esm and commonjs

Package Sidebar

Install

npm i map-ext

Weekly Downloads

26

Version

0.1.5

License

MIT

Unpacked Size

11 kB

Total Files

17

Last publish

Collaborators

  • jaenster