File size: 1,393 Bytes
369fac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @typedef { import('estree').Node} Node
 * @typedef {{
 *   skip: () => void;
 *   remove: () => void;
 *   replace: (node: Node) => void;
 * }} WalkerContext
 */

export class WalkerBase {
	constructor() {
		/** @type {boolean} */
		this.should_skip = false;

		/** @type {boolean} */
		this.should_remove = false;

		/** @type {Node | null} */
		this.replacement = null;

		/** @type {WalkerContext} */
		this.context = {
			skip: () => (this.should_skip = true),
			remove: () => (this.should_remove = true),
			replace: (node) => (this.replacement = node)
		};
	}

	/**
	 * @template {Node} Parent
	 * @param {Parent | null | undefined} parent
	 * @param {keyof Parent | null | undefined} prop
	 * @param {number | null | undefined} index
	 * @param {Node} node
	 */
	replace(parent, prop, index, node) {
		if (parent && prop) {
			if (index != null) {
				/** @type {Array<Node>} */ (parent[prop])[index] = node;
			} else {
				/** @type {Node} */ (parent[prop]) = node;
			}
		}
	}

	/**
	 * @template {Node} Parent
	 * @param {Parent | null | undefined} parent
	 * @param {keyof Parent | null | undefined} prop
	 * @param {number | null | undefined} index
	 */
	remove(parent, prop, index) {
		if (parent && prop) {
			if (index !== null && index !== undefined) {
				/** @type {Array<Node>} */ (parent[prop]).splice(index, 1);
			} else {
				delete parent[prop];
			}
		}
	}
}