-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmap.go
65 lines (55 loc) · 1.49 KB
/
map.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
57
58
59
60
61
62
63
64
65
package incr
import (
"context"
"fmt"
)
// Map applies a function to a given input incremental and returns
// a new incremental of the output type of that function.
func Map[A, B any](scope Scope, a Incr[A], fn func(A) B) Incr[B] {
return MapContext(scope, a, func(_ context.Context, v A) (B, error) {
return fn(v), nil
})
}
// MapContext applies a function to a given input incremental and returns
// a new incremental of the output type of that function but is context aware
// and can also return an error, aborting stabilization.
func MapContext[A, B any](scope Scope, a Incr[A], fn func(context.Context, A) (B, error)) Incr[B] {
return WithinScope(scope, &mapIncr[A, B]{
n: NewNode("map"),
a: a,
fn: fn,
parents: []INode{a},
})
}
var (
_ Incr[string] = (*mapIncr[int, string])(nil)
_ INode = (*mapIncr[int, string])(nil)
_ IStabilize = (*mapIncr[int, string])(nil)
_ fmt.Stringer = (*mapIncr[int, string])(nil)
)
type mapIncr[A, B any] struct {
n *Node
a Incr[A]
fn func(context.Context, A) (B, error)
val B
parents []INode
}
func (mn *mapIncr[A, B]) Parents() []INode {
return mn.parents
}
func (mn *mapIncr[A, B]) Node() *Node {
return mn.n
}
func (mn *mapIncr[A, B]) Value() B { return mn.val }
func (mn *mapIncr[A, B]) Stabilize(ctx context.Context) (err error) {
var val B
val, err = mn.fn(ctx, mn.a.Value())
if err != nil {
return
}
mn.val = val
return nil
}
func (mn *mapIncr[A, B]) String() string {
return mn.n.String()
}