UNPKG

@spearwolf/twopoint5d

Version:

a library to create 2.5d realtime graphics and pixelart with three.js

81 lines 2.53 kB
export class Dependencies { static { this.cloneable = (name) => [ name, { equals: (a, b) => a.equals(b), clone: (source) => source.clone(), copy: (source, target) => target.copy(source), }, ]; } #props; #callbacks = new Map(); #state = new Map(); constructor(props) { this.#props = props.map((p) => { if (Array.isArray(p)) { if (typeof p[1] === 'function') { const [name, equals] = p; const callbacks = { equals }; this.#callbacks.set(name, callbacks); return [name, callbacks]; } else { this.#callbacks.set(p[0], p[1]); return p; } } else { return [p, undefined]; } }); } update(nextProps) { for (const [name, value] of Object.entries(nextProps)) { if (this.#callbacks.has(name)) { const { clone, copy } = this.#callbacks.get(name); if (value != null && clone != null && copy != null) { const curValue = this.#state.get(name); if (curValue == null) { this.#state.set(name, clone(value)); } else { copy(value, curValue); } continue; } } this.#state.set(name, value); } } equals(nextProps) { for (let i = 0; i < this.#props.length; i++) { const [name, callbacks] = this.#props[i]; const nextValue = nextProps[name]; const curValue = this.#state.get(name); if (curValue == null || nextValue == null) { if (curValue == nextValue) { continue; } return false; } if (curValue !== nextValue && callbacks?.equals?.(curValue, nextValue) === false) { return false; } } return true; } changed(nextProps) { const changed = !this.equals(nextProps); if (changed) { this.update(nextProps); } return changed; } clear() { this.#state.clear(); } value(key) { return this.#state.get(key); } } //# sourceMappingURL=Dependencies.js.map