-
Notifications
You must be signed in to change notification settings - Fork 1
/
map_if.go
56 lines (47 loc) · 1.16 KB
/
map_if.go
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package incr
import (
"context"
"fmt"
)
// MapIf returns an incremental that yields one of two values
// based on the boolean condition returned from a third incremental.
//
// Specifically, we term this [MapIf] because the nodes are all
// linked in the graph, but the value changes during stabilization.
func MapIf[A any](scope Scope, a, b Incr[A], p Incr[bool]) Incr[A] {
return WithinScope(scope, &mapIfIncr[A]{
n: NewNode("map_if"),
a: a,
b: b,
p: p,
})
}
var (
_ Incr[string] = (*mapIfIncr[string])(nil)
_ INode = (*mapIfIncr[string])(nil)
_ IStabilize = (*mapIfIncr[string])(nil)
_ fmt.Stringer = (*mapIfIncr[string])(nil)
)
type mapIfIncr[A any] struct {
n *Node
a Incr[A]
b Incr[A]
p Incr[bool]
value A
}
func (mi *mapIfIncr[T]) Parents() []INode {
return []INode{mi.a, mi.b, mi.p}
}
func (mi *mapIfIncr[A]) Node() *Node { return mi.n }
func (mi *mapIfIncr[A]) Value() A {
return mi.value
}
func (mi *mapIfIncr[A]) Stabilize(ctx context.Context) error {
if mi.p.Value() {
mi.value = mi.a.Value()
} else {
mi.value = mi.b.Value()
}
return nil
}
func (mi *mapIfIncr[A]) String() string { return mi.n.String() }