2021-06-18 13:05:06 +02:00
|
|
|
import AbstractDerivation from './AbstractDerivation'
|
|
|
|
import type {IDerivation} from './IDerivation'
|
|
|
|
|
|
|
|
// Exporting from a function because of the circular dependency with AbstractDerivation
|
|
|
|
const makeMapDerivationClass = () =>
|
2022-11-26 22:40:04 +01:00
|
|
|
// TODO once prism and AbstractDerivation are merged into one, we should delete this file
|
2021-06-18 13:05:06 +02:00
|
|
|
class MapDerivation<T, V> extends AbstractDerivation<V> {
|
|
|
|
constructor(
|
|
|
|
private readonly _dep: IDerivation<T>,
|
|
|
|
private readonly _fn: (t: T) => V,
|
|
|
|
) {
|
|
|
|
super()
|
|
|
|
this._addDependency(_dep)
|
|
|
|
}
|
|
|
|
|
|
|
|
_recalculate() {
|
|
|
|
return this._fn(this._dep.getValue())
|
|
|
|
}
|
|
|
|
|
|
|
|
_reactToDependencyBecomingStale() {}
|
|
|
|
}
|
|
|
|
|
|
|
|
let cls: ReturnType<typeof makeMapDerivationClass> | undefined = undefined
|
|
|
|
|
2022-11-26 15:00:14 +01:00
|
|
|
export default function map<V, R>(
|
2021-06-18 13:05:06 +02:00
|
|
|
dep: IDerivation<V>,
|
|
|
|
fn: (v: V) => R,
|
|
|
|
): IDerivation<R> {
|
|
|
|
if (!cls) {
|
|
|
|
cls = makeMapDerivationClass()
|
|
|
|
}
|
|
|
|
return new cls(dep, fn)
|
|
|
|
}
|