7
7
*/
8
8
class BaseNode {
9
9
constructor ( ) { }
10
+
11
+ equals ( other , ignoredFields = [ "span" ] ) {
12
+ const thisKeys = new Set ( Object . keys ( this ) ) ;
13
+ const otherKeys = new Set ( Object . keys ( other ) ) ;
14
+ if ( ignoredFields ) {
15
+ for ( const fieldName of ignoredFields ) {
16
+ thisKeys . delete ( fieldName ) ;
17
+ otherKeys . delete ( fieldName ) ;
18
+ }
19
+ }
20
+ if ( thisKeys . size !== otherKeys . size ) {
21
+ return false ;
22
+ }
23
+ for ( const fieldName of thisKeys ) {
24
+ if ( ! otherKeys . has ( fieldName ) ) {
25
+ return false ;
26
+ }
27
+ const thisVal = this [ fieldName ] ;
28
+ const otherVal = other [ fieldName ] ;
29
+ if ( typeof thisVal !== typeof otherVal ) {
30
+ return false ;
31
+ }
32
+ if ( thisVal instanceof Array ) {
33
+ if ( thisVal . length !== otherVal . length ) {
34
+ return false ;
35
+ }
36
+ // Sort elements of order-agnostic fields to ensure the
37
+ // comparison is order-agnostic as well. Annotations should be
38
+ // here too but they don't have sorting keys.
39
+ if ( [ "attributes" , "variants" ] . indexOf ( fieldName ) >= 0 ) {
40
+ thisVal . sort ( sorting_key_compare ) ;
41
+ otherVal . sort ( sorting_key_compare ) ;
42
+ }
43
+ for ( let i = 0 , ii = thisVal . length ; i < ii ; ++ i ) {
44
+ if ( ! scalars_equal ( thisVal [ i ] , otherVal [ i ] , ignoredFields ) ) {
45
+ return false ;
46
+ }
47
+ }
48
+ } else if ( ! scalars_equal ( thisVal , otherVal , ignoredFields ) ) {
49
+ return false ;
50
+ }
51
+ }
52
+ return true ;
53
+ }
10
54
}
11
55
12
56
/*
@@ -18,6 +62,23 @@ class SyntaxNode extends BaseNode {
18
62
}
19
63
}
20
64
65
+ function scalars_equal ( thisVal , otherVal , ignoredFields ) {
66
+ if ( thisVal instanceof BaseNode ) {
67
+ return thisVal . equals ( otherVal , ignoredFields ) ;
68
+ }
69
+ return thisVal === otherVal ;
70
+ }
71
+
72
+ function sorting_key_compare ( left , right ) {
73
+ if ( left . sorting_key < right . sorting_key ) {
74
+ return - 1 ;
75
+ }
76
+ if ( left . sorting_key === right . sorting_key ) {
77
+ return 0 ;
78
+ }
79
+ return 1 ;
80
+ }
81
+
21
82
export class Resource extends SyntaxNode {
22
83
constructor ( body = [ ] ) {
23
84
super ( ) ;
@@ -166,6 +227,10 @@ export class Attribute extends SyntaxNode {
166
227
this . id = id ;
167
228
this . value = value ;
168
229
}
230
+
231
+ get sorting_key ( ) {
232
+ return this . id . name ;
233
+ }
169
234
}
170
235
171
236
export class Variant extends SyntaxNode {
@@ -176,6 +241,13 @@ export class Variant extends SyntaxNode {
176
241
this . value = value ;
177
242
this . default = def ;
178
243
}
244
+
245
+ get sorting_key ( ) {
246
+ if ( this . key instanceof NumberExpression ) {
247
+ return this . key . value ;
248
+ }
249
+ return this . key . name ;
250
+ }
179
251
}
180
252
181
253
export class NamedArgument extends SyntaxNode {
0 commit comments