This repository has been archived on 2022-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
hydrogen-web/src/observable/map/FilteredMap.js
Bruno Windels 001dbefbcf stop using default exports
because it becomes hard to remember where you used them and where not
2020-04-20 21:26:39 +02:00

57 lines
1.5 KiB
JavaScript

import {BaseObservableMap} from "./BaseObservableMap.js";
export class FilteredMap extends BaseObservableMap {
constructor(source, mapper, updater) {
super();
this._source = source;
this._mapper = mapper;
this._updater = updater;
this._mappedValues = new Map();
}
onAdd(key, value) {
const mappedValue = this._mapper(value);
this._mappedValues.set(key, mappedValue);
this.emitAdd(key, mappedValue);
}
onRemove(key, _value) {
const mappedValue = this._mappedValues.get(key);
if (this._mappedValues.delete(key)) {
this.emitRemove(key, mappedValue);
}
}
onChange(key, value, params) {
const mappedValue = this._mappedValues.get(key);
if (mappedValue !== undefined) {
const newParams = this._updater(value, params);
if (newParams !== undefined) {
this.emitChange(key, mappedValue, newParams);
}
}
}
onSubscribeFirst() {
for (let [key, value] of this._source) {
const mappedValue = this._mapper(value);
this._mappedValues.set(key, mappedValue);
}
super.onSubscribeFirst();
}
onUnsubscribeLast() {
super.onUnsubscribeLast();
this._mappedValues.clear();
}
onReset() {
this._mappedValues.clear();
this.emitReset();
}
[Symbol.iterator]() {
return this._mappedValues.entries()[Symbol.iterator];
}
}