@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
139 lines (115 loc) • 2.45 kB
JavaScript
import { assert } from "../assert.js";
import Signal from "../events/signal/Signal.js";
import { computeStringHash } from "../primitives/strings/computeStringHash.js";
/**
*
* @author Alex Goldring
* @copyright Company Named Limited (c) 2025
*/
class ObservedString extends String {
/**
*
* @param {string} [value]
* @constructor
*/
constructor(value = "") {
super();
assert.isString(value, 'value');
/**
*
* @type {String}
* @private
*/
this.__value = value;
this.onChanged = new Signal();
}
/**
*
* @returns {String}
*/
valueOf() {
return this.__value;
}
/**
*
* @returns {String}
*/
toString() {
return this.__value;
}
/**
*
* @param {String} value
* @returns {ObservedString}
*/
set(value) {
assert.isString(value, 'value');
const oldValue = this.__value;
if (oldValue !== value) {
this.__value = value;
this.onChanged.send2(value, oldValue);
}
return this;
}
/**
*
* @param {ObservedString} other
*/
copy(other) {
this.set(other.getValue());
}
/**
*
* @param {ObservedString} other
* @returns {boolean}
*/
equals(other) {
return this.__value === other.__value;
}
/**
*
* @returns {String}
*/
getValue() {
return this.__value;
}
/**
*
* @param {function} f
*/
process(f) {
f(this.getValue());
this.onChanged.add(f);
}
toJSON() {
return this.__value;
}
fromJSON(obj) {
this.set(obj);
}
/**
*
* @param {BinaryBuffer} buffer
*/
toBinaryBuffer(buffer) {
buffer.writeUTF8String(this.__value);
}
/**
*
* @param {BinaryBuffer} buffer
*/
fromBinaryBuffer(buffer) {
const value = buffer.readUTF8String();
this.set(value);
}
hash() {
return computeStringHash(this.__value);
}
}
/**
* Used for optimized "instanceof" check
* @readonly
* @type {boolean}
*/
ObservedString.prototype.isObservedString = true;
export default ObservedString;