Repository navigation
Expand file tree
/
Copy pathtrackformutations.go
More file actions
276 lines (249 loc) · 7.15 KB
/
Copy pathtrackformutations.go
File metadata and controls
276 lines (249 loc) · 7.15 KB
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package invariant
import "strings"
// MutationResult is the value returned by Tracker.DetectMutations. It mirrors
// the JS return shapes `{wasMutated: true, path: [...]}` and `{wasMutated:
// false}`.
//
// When WasMutated is false, Path is nil (the original object omits the `path`
// key entirely in that case).
type MutationResult struct {
WasMutated bool
Path []string
}
// trackedProperty is the snapshot node built by trackProperties. It mirrors the
// JS `{ value, children }` shape.
//
// children is nil when the value was immutable at snapshot time (the JS object
// simply lacks a `children` key in that case).
type trackedProperty struct {
value Value
children map[string]*trackedProperty
// childKeys preserves the enumeration order of children so detection can
// reproduce JS key ordering.
childKeys []string
}
// Tracker snapshots a state tree and can later report whether it was mutated in
// place. It is the Go equivalent of the object returned by the JS
// `trackForMutations` function, exposing a single DetectMutations method.
type Tracker struct {
isImmutable IsImmutableFunc
ignore []string
tracked *trackedProperty
obj Value
}
// TrackForMutations snapshots obj and returns a Tracker. This is a direct port
// of the JS `trackForMutations(isImmutable, ignore, obj)` factory.
//
// A nil isImmutable defaults to IsImmutableDefault, matching the JS default
// binding performed by the middleware.
func TrackForMutations(isImmutable IsImmutableFunc, ignore []string, obj Value) *Tracker {
if isImmutable == nil {
isImmutable = IsImmutableDefault
}
return &Tracker{
isImmutable: isImmutable,
ignore: ignore,
tracked: trackProperties(isImmutable, ignore, obj, nil),
obj: obj,
}
}
// DetectMutations reports whether the tracked object has been mutated in place
// since it was snapshotted. Port of the returned `detectMutations()` closure.
func (t *Tracker) DetectMutations() MutationResult {
return detectMutations(t.isImmutable, t.ignore, t.tracked, t.obj, false, nil)
}
// trackProperties recursively snapshots obj. Port of the JS `trackProperties`.
//
// path is the accumulated key path (nil at the root, matching the JS default
// `path = []`).
func trackProperties(isImmutable IsImmutableFunc, ignore []string, obj Value, path []string) *trackedProperty {
tracked := &trackedProperty{value: obj}
if !isImmutable(obj) {
tracked.children = map[string]*trackedProperty{}
for _, key := range ownKeys(obj) {
childPath := appendPath(path, key)
if len(ignore) > 0 && contains(ignore, strings.Join(childPath, ".")) {
continue
}
tracked.children[key] = trackProperties(
isImmutable,
ignore,
propertyValue(obj, key),
childPath,
)
tracked.childKeys = append(tracked.childKeys, key)
}
}
return tracked
}
// detectMutations recursively compares the current obj against its snapshot.
// Port of the JS `detectMutations`.
//
// sameParentRef reports whether the parent reference was unchanged; path is the
// accumulated key path.
func detectMutations(
isImmutable IsImmutableFunc,
ignore []string,
tracked *trackedProperty,
obj Value,
sameParentRef bool,
path []string,
) MutationResult {
var prevObj Value = Undefined
if tracked != nil {
prevObj = tracked.value
}
sameRef := refEqual(prevObj, obj)
if sameParentRef && !sameRef && !isNaNValue(obj) {
return MutationResult{WasMutated: true, Path: path}
}
if isImmutable(prevObj) || isImmutable(obj) {
return MutationResult{WasMutated: false}
}
// Gather all keys from prev (tracked) and after objs, mirroring the JS
// union that seeds `keysToDetect` from tracked children first, then from
// the current object.
keys := unionKeys(tracked, obj)
for i := 0; i < len(keys); i++ {
key := keys[i]
childPath := appendPath(path, key)
if len(ignore) > 0 && contains(ignore, strings.Join(childPath, ".")) {
continue
}
var childTracked *trackedProperty
if tracked != nil && tracked.children != nil {
childTracked = tracked.children[key]
}
result := detectMutations(
isImmutable,
ignore,
childTracked,
propertyValue(obj, key),
sameRef,
childPath,
)
if result.WasMutated {
return result
}
}
return MutationResult{WasMutated: false}
}
// unionKeys reproduces the JS `keysToDetect` object: keys from the tracked
// children (in their tracked order) followed by any additional own keys present
// on the current object, preserving first-seen order and de-duplicating.
func unionKeys(tracked *trackedProperty, obj Value) []string {
seen := map[string]bool{}
var keys []string
if tracked != nil {
for _, k := range tracked.childKeys {
if !seen[k] {
seen[k] = true
keys = append(keys, k)
}
}
}
for _, k := range ownKeys(obj) {
if !seen[k] {
seen[k] = true
keys = append(keys, k)
}
}
return keys
}
// ownKeys returns the own enumerable keys of a container value, mirroring
// Object.keys / for..in. Non-containers have no enumerable keys.
func ownKeys(v Value) []string {
switch c := v.(type) {
case *Obj:
return c.Keys()
case *Arr:
return c.Keys()
default:
return nil
}
}
// propertyValue reads obj[key], returning Undefined for a missing key or a
// non-container, mirroring JS property access which yields `undefined`.
func propertyValue(v Value, key string) Value {
switch c := v.(type) {
case *Obj:
if child, ok := c.Get(key); ok {
return child
}
return Undefined
case *Arr:
idx, ok := parseIndex(key)
if ok && idx >= 0 && idx < c.Len() {
return c.At(idx)
}
return Undefined
default:
return Undefined
}
}
// refEqual reproduces JS `===` for the values that flow through detection.
// Containers compare by reference (pointer identity); primitives compare by
// value. NaN !== NaN, matching IEEE-754 / JS semantics.
func refEqual(a, b Value) bool {
switch av := a.(type) {
case *Obj:
bv, ok := b.(*Obj)
return ok && av == bv
case *Arr:
bv, ok := b.(*Arr)
return ok && av == bv
case Str:
bv, ok := b.(Str)
return ok && av == bv
case Num:
bv, ok := b.(Num)
// NaN is never equal to itself, matching JS `===`.
return ok && !isNaNValue(av) && !isNaNValue(bv) && av == bv
case Bool:
bv, ok := b.(Bool)
return ok && av == bv
case nullType:
_, ok := b.(nullType)
return ok
case undefinedType:
_, ok := b.(undefinedType)
return ok
case nil:
return b == nil
default:
return false
}
}
// appendPath returns a new slice with key appended, never aliasing the caller's
// backing array. Mirrors the JS `path.concat(key)` which always allocates.
func appendPath(path []string, key string) []string {
next := make([]string, len(path)+1)
copy(next, path)
next[len(path)] = key
return next
}
// contains reports whether needle is present in haystack.
func contains(haystack []string, needle string) bool {
for _, s := range haystack {
if s == needle {
return true
}
}
return false
}
// parseIndex parses a non-negative decimal array index. Mirrors JS array index
// coercion for the string keys produced by Arr.Keys.
func parseIndex(s string) (int, bool) {
if s == "" {
return 0, false
}
n := 0
for i := 0; i < len(s); i++ {
c := s[i]
if c < '0' || c > '9' {
return 0, false
}
n = n*10 + int(c-'0')
}
return n, true
}