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

1.0.6 • Public • Published

LoudMap

LoudMap extends the JS Map class to support state management. LoudMap supports computed properties, and it has an EventEmitter for notifying the user of state changes.

Deno import

  • latest - import { EventEmitter } from "https://gitlab.com/rhythnic/loud-map/-/raw/master/src/mod.ts"
  • versioned - import { EventEmitter } from "https://gitlab.com/rhythnic/loud-map/-/raw/VERSION/src/mod.ts"

NPM install

npm install loud-map

Usage

import { LoudMap } from 'loud-map'

const state = new LoudMap()

state.compute('menuClosed', ['menuOpen'], menuOpen => !menuOpen)

state.compute('user', ['userId'], async (userId) => {
  if (!userId) return null
  return fetch(`/users/${userId}`).then(res => res.json())
})

state.events.on('change/menuOpen', (value, oldValue) => {
  // ...
})

state.events.on('change', (changes) => {
  // changes is an object with all changed key/value pairs
})

state.batch({
  userId: '',
  menuOpen: false
})

// state.get('menuOpen') === false
state.set('menuOpen', true)

API

batch(values)

Set many values at once. An change/KEY is emitted for each key in values. One change event is emitted at the end, with the values object as the payload. You can delete a key via batch by passing undefined or void 0 as the value.

compute(key, dependencyKeys, computeHandler)

  • key String - key at which to cache computed value in the map
  • dependencyKeys Array - map keys on which this computed value depends
  • computeHandler Function - function to compute a value

The computeHandler will receive all of the values of it's dependencyKeys as arguments. A computeHandler can return a Promise. In this case, the promise is cached. Computed properties are lazy. The computeFunction doesn't run until it is accessed with get. The result is cached in the map, so future access won't trigger recomputation. If the value of a dependencyKey changes, the computed value is deleted from cache and computed again next time it is accessed.

from(map)

Convert a regular Map into a LoudMap

Events

  • If the user calls the set method, two events are emitted, change/KEY and change.
  • If the user calls the batch method, one change/KEY event is emitted for each key, and one change event is emitted at the end.
  • Calling delete will emit the same events as set

Contributing

Please use issues for all bug reports and feature requests.

LICENSE

MIT license, Copyright Nicholas Baroni 2020

Package Sidebar

Install

npm i loud-map

Weekly Downloads

0

Version

1.0.6

License

MIT

Unpacked Size

9.88 kB

Total Files

8

Last publish

Collaborators

  • nbaroni