-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathremoveNode.js
55 lines (46 loc) · 1.31 KB
/
removeNode.js
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
const keys = {
ObjectExpression: 'properties',
Program: 'body'
};
const offsets = {
ObjectExpression: [ 1, -1 ],
Program: [ 0, 0 ]
};
export function removeNode ( code, parent, node ) {
const key = keys[ parent.type ];
const offset = offsets[ parent.type ];
if ( !key || !offset ) throw new Error( `not implemented: ${parent.type}` );
const list = parent[ key ];
const i = list.indexOf( node );
if ( i === -1 ) throw new Error( 'node not in list' );
let a;
let b;
if ( list.length === 1 ) {
// remove everything, leave {}
a = parent.start + offset[0];
b = parent.end + offset[1];
} else if ( i === 0 ) {
// remove everything before second node, including comments
a = parent.start + offset[0];
while ( /\s/.test( code.original[a] ) ) a += 1;
b = list[i].end;
while ( /[\s,]/.test( code.original[b] ) ) b += 1;
} else {
// remove the end of the previous node to the end of this one
a = list[ i - 1 ].end;
b = node.end;
}
code.remove( a, b );
list.splice( i, 1 );
return;
}
export function removeObjectKey ( code, node, key ) {
if ( node.type !== 'ObjectExpression' ) return;
let i = node.properties.length;
while ( i-- ) {
const property = node.properties[i];
if ( property.key.type === 'Identifier' && property.key.name === key ) {
removeNode( code, node, property );
}
}
}