Debian Codegraph @

packages/babel-types/src/validators/isNodesEquivalent.ts

raw
1 import { NODE_FIELDS, VISITOR_KEYS } from "../definitions";
2 import type * as t from "..";
3
4 /**
5 * Check if two nodes are equivalent
6 */
7 export default function isNodesEquivalent<T extends Partial<t.Node>>(
8 a: T,
9 b: any,
10 ): b is T {
11 if (
12 typeof a !== "object" ||
13 typeof b !== "object" ||
14 a == null ||
15 b == null
16 ) {
17 return a === b;
18 }
19
20 if (a.type !== b.type) {
21 return false;
22 }
23
24 const fields = Object.keys(NODE_FIELDS[a.type] || a.type);
25 const visitorKeys = VISITOR_KEYS[a.type];
26
27 for (const field of fields) {
28 const val_a =
29 // @ts-expect-error field must present in a
30 a[field];
31 const val_b = b[field];
32 if (typeof val_a !== typeof val_b) {
33 return false;
34 }
35 if (val_a == null && val_b == null) {
36 continue;
37 } else if (val_a == null || val_b == null) {
38 return false;
39 }
40
41 if (Array.isArray(val_a)) {
42 if (!Array.isArray(val_b)) {
43 return false;
44 }
45 if (val_a.length !== val_b.length) {
46 return false;
47 }
48
49 for (let i = 0; i < val_a.length; i++) {
50 if (!isNodesEquivalent(val_a[i], val_b[i])) {
51 return false;
52 }
53 }
54 continue;
55 }
56
57 if (typeof val_a === "object" && !visitorKeys?.includes(field)) {
58 for (const key of Object.keys(val_a)) {
59 if (val_a[key] !== val_b[key]) {
60 return false;
61 }
62 }
63 continue;
64 }
65
66 if (!isNodesEquivalent(val_a, val_b)) {
67 return false;
68 }
69 }
70
71 return true;
72 }