UNPKG

@woosh/meep-engine

Version:

Pure JavaScript game engine. Fully featured and production ready.

100 lines (83 loc) 2.18 kB
import { assert } from "../assert.js"; import Signal from "../events/signal/Signal.js"; class ObservedEnum { /** * @template T * @param {T} value * @param {Object.<string,T>} validSet * @constructor */ constructor(value, validSet) { assert.equal(typeof validSet, "object", `ValidSet must be of type "object", instead was ${typeof validSet}`); assert.notEqual(Object.values(validSet).indexOf(value), -1, `Value must be one of [${Object.values(validSet).join(", ")}], instead was "${value}"`); /** * * @type {T} * @private */ this.__value = value; this.__validSet = validSet; this.onChanged = new Signal(); } /** * * @returns {Object<string, T>} */ getValidValueSet() { return this.__validSet; } /** * * @param {T} value * @returns {ObservedEnum} */ set(value) { assert.notEqual(Object.values(this.__validSet).indexOf(value), -1, `Value must be one of [${Object.values(this.__validSet).join(", ")}], instead was "${value}"`); const oldValue = this.__value; if (oldValue !== value) { this.__value = value; this.onChanged.dispatch(value, oldValue); } return this; } /** * @template X * @param {ObservedEnum<X>} other * @returns {boolean} */ equals(other) { return this.__value === other.__value; } /** * * @param {ObservedEnum} other */ copy(other) { this.set(other.getValue()); } /** * * @returns {T} */ getValue() { return this.__value; } invert() { this.set(!this.__value); } /** * * @param {function(T,T)} processor */ process(processor) { this.onChanged.add(processor); processor(this.__value, this.__value); } toJSON() { return this.__value; } fromJSON(obj) { this.set(obj); } } export default ObservedEnum;