-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
107 lines (94 loc) · 2.75 KB
/
index.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
var parse = require('esprima').parse;
var objectKeys = Object.keys || function(obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
};
var forEach = function(xs, fn) {
if (xs.forEach) return xs.forEach(fn);
for (var i = 0; i < xs.length; i++) {
fn.call(xs, xs[i], i, xs);
}
};
var isArray = Array.isArray || function(xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
module.exports = function(src, opts, fn) {
if (typeof opts === 'function') {
fn = opts;
opts = {};
}
if (typeof src === 'object') {
opts = src;
src = opts.source;
delete opts.source;
}
src = src === undefined ? opts.source : src;
opts.range = true;
if (typeof src !== 'string') src = String(src);
try {
var ast = parse(src, opts);
} catch (err) {
// console.log("error trying to parse " + err + src);
return undefined;
}
var result = {
chunks: src.split(''),
oldchunks: src.split(''),
toString: function() {
return result.chunks.join('')
},
inspect: function() {
return result.toString()
}
};
var index = 0;
(function walk(node, parent) {
insertHelpers(node, parent, result.chunks, result.oldchunks);
forEach(objectKeys(node), function(key) {
if (key === 'parent') return;
var child = node[key];
if (isArray(child)) {
forEach(child, function(c) {
if (c && typeof c.type === 'string') {
walk(c, node);
}
});
} else if (child && typeof child.type === 'string') {
insertHelpers(child, node, result.chunks, result.oldchunks);
walk(child, node);
}
});
fn(node);
})(ast, undefined);
return result;
};
function insertHelpers(node, parent, chunks, oldchunks) {
if (!node.range) return;
node.parent = parent;
node.source = function() {
return chunks.slice(
node.range[0], node.range[1]
).join('');
};
node.oldsource = function() {
return oldchunks.slice(
node.range[0], node.range[1]
).join('');
};
if (node.update && typeof node.update === 'object') {
var prev = node.update;
forEach(objectKeys(prev), function(key) {
update[key] = prev[key];
});
node.update = update;
} else {
node.update = update;
}
function update(s) {
chunks[node.range[0]] = s;
for (var i = node.range[0] + 1; i < node.range[1]; i++) {
chunks[i] = '';
}
};
}