UNPKG

@mittwald/react-use-promise

Version:

Simple and declarative use of Promises in your React components. Observe their state and refresh them in various advanced ways.

42 lines (41 loc) 1.18 kB
import { Minimatch } from "minimatch"; export class Store { entries = new Map(); constructor() { } getOrSet(id, dataBuilder, options = {}) { const { tags = [] } = options; const existing = this.entries.get(id); if (existing) { return existing.data; } const newData = dataBuilder(); this.entries.set(id, { data: newData, tags, }); return newData; } set(id, dataBuilder, options = {}) { this.getOrSet(id, dataBuilder, options); } get(id) { return this.entries.get(id)?.data; } findBy(matcher) { return this.getAll().filter(matcher); } getAll(tag) { const entriesArray = Array.from(this.entries.values()); if (tag === undefined) { return entriesArray.map((e) => e.data); } const mm = new Minimatch(tag); const testSomeTagsMatchingPattern = (tags) => tags.some((t) => mm.match(t)); return entriesArray .filter((e) => testSomeTagsMatchingPattern(e.tags)) .map((e) => e.data); } clear() { this.entries.clear(); } }