-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathmapFacetArrayCached.ts
31 lines (27 loc) · 1.08 KB
/
mapFacetArrayCached.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { EqualityCheck, Facet, NO_VALUE, NoValue } from '../types'
import { mapIntoObserveArray } from './mapIntoObserveArray'
import { createFacet } from '../facet'
export function mapFacetArrayCached<M>(
facets: Facet<unknown>[],
fn: (...value: unknown[]) => M | NoValue,
equalityCheck?: EqualityCheck<M>,
): Facet<M> {
const cachedFacet = createFacet<M>({
// pass the equalityCheck to the mapIntoObserveArray to prevent even triggering the observable
startSubscription: mapIntoObserveArray(facets, fn, equalityCheck),
initialValue: NO_VALUE,
})
return {
get: () => {
const cachedValue = cachedFacet.get()
if (cachedValue !== NO_VALUE) return cachedValue
const dependencyValues = facets.map((facet) => facet.get())
const hasAllValues = dependencyValues.reduce<boolean>((acc, value) => acc && value !== NO_VALUE, true)
if (!hasAllValues) return NO_VALUE
const mappedValue = fn(...dependencyValues)
if (mappedValue !== NO_VALUE) cachedFacet.set(mappedValue)
return mappedValue
},
observe: cachedFacet.observe,
}
}