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
+ }
49
+ else if ( ! scalars_equal ( thisVal , otherVal , ignoredFields ) ) {
50
+ return false ;
51
+ }
52
+ }
53
+ return true ;
54
+ }
10
55
}
11
56
12
57
/*
@@ -18,6 +63,23 @@ class SyntaxNode extends BaseNode {
18
63
}
19
64
}
20
65
66
+ function scalars_equal ( thisVal , otherVal , ignoredFields ) {
67
+ if ( thisVal instanceof BaseNode ) {
68
+ return thisVal . equals ( otherVal , ignoredFields ) ;
69
+ }
70
+ return thisVal === otherVal ;
71
+ }
72
+
73
+ function sorting_key_compare ( left , right ) {
74
+ if ( left . sorting_key < right . sorting_key ) {
75
+ return - 1 ;
76
+ }
77
+ if ( left . sorting_key === right . sorting_key ) {
78
+ return 0 ;
79
+ }
80
+ return 1 ;
81
+ }
82
+
21
83
export class Resource extends SyntaxNode {
22
84
constructor ( body = [ ] ) {
23
85
super ( ) ;
@@ -166,6 +228,10 @@ export class Attribute extends SyntaxNode {
166
228
this . id = id ;
167
229
this . value = value ;
168
230
}
231
+
232
+ get sorting_key ( ) {
233
+ return this . id . name ;
234
+ }
169
235
}
170
236
171
237
export class Variant extends SyntaxNode {
@@ -176,6 +242,13 @@ export class Variant extends SyntaxNode {
176
242
this . value = value ;
177
243
this . default = def ;
178
244
}
245
+
246
+ get sorting_key ( ) {
247
+ if ( this . key instanceof NumberExpression ) {
248
+ return this . key . value ;
249
+ }
250
+ return this . key . name ;
251
+ }
179
252
}
180
253
181
254
export class NamedArgument extends SyntaxNode {
0 commit comments