forked from endel/js2php
-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.js
87 lines (72 loc) · 2.19 KB
/
utils.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
module.exports = {
//
// classize:
//
// Example
// input: 'some.module.name'
// output: '\Some\Module\Name'
//
classize: function (string) {
var modules = string.split(".");
if (modules.length == 1) {
return string.charAt(0).toUpperCase() + string.slice(1);
} else {
var m = [];
for (var i=0; i<modules.length; i++) {
m.push(this.classize(modules[i]));
}
return m.join("\\");
}
},
stringify: function(string, forceDoubleQuote) {
if (/^[ -&\(-~]*$/.test(string) && !forceDoubleQuote) {
/* can use an efficient single-quoted string */
return "'" + string.replace(/'|(?:\\(?=[\\']|$))/g, '\\$&') + "'";
}
// double-quoted string (but protect $ before possible variable names)
return JSON.stringify(string).replace(/\$(?=[{a-zA-Z_\x80-\xff])/g, '\\$');
},
clone: function(obj) {
var parent = null, response = null;
// prevent circular loop when cloning the obj.
if (obj.parent) {
parent = obj.parent;
delete obj.parent;
}
response = JSON.parse(JSON.stringify(obj));
// keep original parent
if (parent) { obj.parent = parent; }
return response;
},
isString: function(node) {
return (node.type == "Literal" && node.raw.match(/^['|"]/)) ||
node.dataType === 'String';
},
isRegExp: function(node) {
var value = node.raw;
if (value.match(/^['"].+['"]$/)) {
value = value.substr(1, node.raw.length-2);
}
var isRegExp = value.match(/^\/(?:[^\/]|\\.)+\/[gimy]+?$/);
if (isRegExp) {
node.raw.value = "'" + value + "'";
node.dataType = 'RegExp';
}
return isRegExp;
},
isType: function(node, type) {
return node &&
(typeof(type)==='string' ? (type===node.type) : type.test(node.type));
},
isId: function(node, id) {
return module.exports.isType(node, 'Identifier') &&
(typeof(id)==='string' ? (id===node.name) : id.test(node.name));
},
// utility function for core library definitions
coreAddHash: function(exports, className) {
Object.keys(exports).forEach(function(name) {
if (/[#.]/.test(name)) { return; }
exports[className + '#' + name] = exports[name];
});
},
}