summaryrefslogtreecommitdiff
path: root/go/react/react.go
blob: 069d7bec82256a34b78d8996732edad9b8cc9847 (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package react

import "log"

const testVersion = 4

type react struct {
}

type inputCell struct {
	cell
}

type compuCell struct {
	cell
	cb map[CallbackHandle]func(int)
}

type com struct {
	eval, ok chan bool
}

type cell struct {
	value    int
	observer []com
}

func New() Reactor {
	return &react{}
}

func (r *react) CreateCompute1(c Cell, f func(int) int) ComputeCell {
	ch := make(chan bool)
	ok := make(chan bool)
	cc := &compuCell{
		cb: make(map[CallbackHandle]func(int)),
	}
	cc.value = f(c.Value())
	Register(c, ch, ok)
	go func() {
		for range ch {
			log.Println("got", c.Value())
			old := cc.value
			cc.value = f(c.Value())
			if old != cc.value {
				for _, ch := range cc.observer {
					log.Println("notify #1")
					ch.eval <- true
					<-ch.ok
				}
				for _, cb := range cc.cb {
					log.Println("cb #1")
					cb(cc.value)
				}
			}
			ok <- true
		}
	}()
	return cc
}

func (r *react) CreateCompute2(c1, c2 Cell, f func(int, int) int) ComputeCell {
	ch := make(chan bool)
	ok := make(chan bool)
	cc := &compuCell{
		cb: make(map[CallbackHandle]func(int)),
	}
	cc.value = f(c1.Value(), c2.Value())
	Register(c1, ch, ok)
	Register(c2, ch, ok)
	go func() {
		for range ch {
			old := cc.value
			cc.value = f(c1.Value(), c2.Value())
			if old != cc.value {
				for _, ch := range cc.observer {
					log.Println("notify #2")
					ch.eval <- true
					<-ch.ok
				}
				for _, cb := range cc.cb {
					log.Println("cb #2")
					cb(cc.value)
				}
			}
			ok <- true
		}
	}()
	return cc
}

func (r *react) CreateInput(i int) InputCell {
	return &inputCell{
		cell: cell{value: i},
	}
}

func (c *compuCell) AddCallback(f func(int)) CallbackHandle {
	c.cb[&f] = f
	return &f
}

func (c *compuCell) RemoveCallback(h CallbackHandle) {
	delete(c.cb, h)
}

func (c *inputCell) SetValue(i int) {
	old := c.value
	c.value = i
	if old != c.value {
		for _, ch := range c.observer {
			log.Println("notify", i)
			ch.eval <- true
			<-ch.ok
		}
	}
}

func (c *cell) Value() int {
	v := c.value
	log.Println("report", v)
	return v
}

func Register(c Cell, ch, ok chan bool) {
	switch v := c.(type) {
	case *compuCell:
		v.observer = append(v.observer, com{ch, ok})
	case *inputCell:
		v.observer = append(v.observer, com{ch, ok})
	}
}