Skip to content

Commit c3b1250

Browse files
committed
A
1 parent 435557a commit c3b1250

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

Diff for: src/utility/check-func.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
function checkPattern(code, pattern) {
2+
let i = 0
3+
let j = 0
4+
while (i < code.length && j < pattern.length) {
5+
if (code[i] == pattern[j]) {
6+
++j
7+
}
8+
++i
9+
}
10+
return j == pattern.length
11+
}
12+
13+
export default {
14+
checkPattern,
15+
}

Diff for: src/utility/safe-func.js

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import * as t from '@babel/types'
2+
3+
function safeDeleteNode(name, path) {
4+
let binding
5+
if (path.isFunctionDeclaration()) {
6+
binding = path.parentPath.scope.getBinding(name)
7+
} else {
8+
binding = path.scope.getBinding(name)
9+
}
10+
if (!binding) {
11+
return false
12+
}
13+
binding.scope.crawl()
14+
binding = binding.scope.getBinding(name)
15+
if (binding.references) {
16+
return false
17+
}
18+
for (const item of binding.constantViolations) {
19+
item.remove()
20+
}
21+
const decl = binding.path
22+
if (decl.removed) {
23+
return true
24+
}
25+
if (!decl.isVariableDeclarator() && !decl.isFunctionDeclaration()) {
26+
return true
27+
}
28+
binding.path.remove()
29+
return true
30+
}
31+
32+
function safeGetLiteral(path) {
33+
if (path.isUnaryExpression()) {
34+
if (path.node.operator === '-' && path.get('argument').isNumericLiteral()) {
35+
return -1 * path.get('argument').node.value
36+
}
37+
return null
38+
}
39+
if (path.isLiteral()) {
40+
return path.node.value
41+
}
42+
return null
43+
}
44+
45+
function safeGetName(path) {
46+
if (path.isIdentifier()) {
47+
return path.node.name
48+
}
49+
if (path.isLiteral()) {
50+
return path.node.value
51+
}
52+
return null
53+
}
54+
55+
function safeReplace(path, value) {
56+
if (typeof value === 'string') {
57+
path.replaceWith(t.stringLiteral(value))
58+
return
59+
}
60+
if (typeof value === 'number') {
61+
path.replaceWith(t.numericLiteral(value))
62+
return
63+
}
64+
path.replaceWithSourceString(value)
65+
}
66+
67+
export default {
68+
safeDeleteNode,
69+
safeGetLiteral,
70+
safeGetName,
71+
safeReplace,
72+
}

0 commit comments

Comments
 (0)