UNPKG

tiny-bin

Version:

A library for building tiny and beautiful command line apps.

50 lines (49 loc) 1.42 kB
/* IMPORT */ import Addon from './addon.js'; import { getClosest } from '../utils.js'; /* MAIN */ class Collection extends Addon { constructor() { /* VARIABLES */ super(...arguments); this.list = []; this.map = new Map(); } /* API */ getAll() { return this.list; } getById(id) { return this.getByIds([id])?.value; } getByIdOrFail(id) { const value = this.getById(id); if (value) return value; const ids = Array.from(this.map.keys()); const closest = getClosest(ids, id, 3, true); this.bin.fail(`Not found "${id}"${closest ? `. Did you mean "${closest}"?` : ''}`); } getByIds(ids) { for (const id of ids) { const value = this.map.get(id); if (value) return { id, value }; } } register(value, override = false) { const existing = this.getByIds(value.ids); if (existing && override) { const index = this.list.indexOf(existing.value); existing.value.ids.forEach(id => this.map.delete(id)); value.ids.forEach(id => this.map.set(id, value)); this.list.splice(index, 1, value); } else { value.ids.forEach(id => this.map.set(id, value)); this.list.push(value); } } } /* EXPORT */ export default Collection;