class ObservableV2 {
constructor(initialValue) {
this._value = initialValue;
this.observers = [];
this.sources = [];
}
read() {
return this._value;
}
write(newValue) {
if (newValue !== this._value) {
this._value = newValue;
this.notifyObservers();
}
}
subscribe(observer) {
this.observers.push(observer);
}
notifyObservers() {
this.observers.forEach(observer => observer(this._value));
}
removeParentObservers(index) {
if (!this.sources) return;
for (let i = index; i < this.sources.length; i++) {
const source = this.sources[i];
const swap = source.observers.findIndex((v) => v === this);
source.observers[swap] = source.observers[source.observers.length - 1];
source.observers.pop();
}
}
}