Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

pass chunks as a param, flatten the code

  • Loading branch information...
commit e01ec716b71a37bb4ba17d8e9ccb183fc4e8e6b0 1 parent 7837895
@substack authored
Showing with 36 additions and 33 deletions.
  1. +32 −32 index.js
  2. +4 −1 test/for.js
View
64 index.js
@@ -19,38 +19,8 @@ module.exports = function (src, fn) {
};
var index = 0;
- function insertHelpers (node, parent) {
- if (!node.range) return;
-
- node.parent = parent;
-
- node.source = function () {
- return result.chunks.slice(
- node.range[0], node.range[1] + 1
- ).join('');
- };
-
- if (typeof node.update === 'object') {
- var prev = node.update;
- Object.keys(prev).forEach(function (key) {
- update[key] = prev[key];
- });
- node.update = update;
- }
- else {
- node.update = update;
- }
-
- function update (s) {
- result.chunks[node.range[0]] = s;
- for (var i = node.range[0] + 1; i < node.range[1] + 1; i++) {
- result.chunks[i] = '';
- }
- };
- }
-
(function walk (node, parent) {
- insertHelpers(node, parent);
+ insertHelpers(node, parent, result.chunks);
Object.keys(node).forEach(function (key) {
if (key === 'parent') return;
@@ -64,7 +34,7 @@ module.exports = function (src, fn) {
});
}
else if (child && typeof child.type === 'string') {
- insertHelpers(child, node);
+ insertHelpers(child, node, result.chunks);
walk(child, node);
}
});
@@ -73,3 +43,33 @@ module.exports = function (src, fn) {
return result;
};
+
+function insertHelpers (node, parent, chunks) {
+ if (!node.range) return;
+
+ node.parent = parent;
+
+ node.source = function () {
+ return chunks.slice(
+ node.range[0], node.range[1] + 1
+ ).join('');
+ };
+
+ if (typeof node.update === 'object') {
+ var prev = node.update;
+ Object.keys(prev).forEach(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] + 1; i++) {
+ chunks[i] = '';
+ }
+ };
+}
View
5 test/for.js
@@ -3,7 +3,7 @@ var test = require('tap').test;
var vm = require('vm');
test('for loop', function (t) {
- t.plan(2);
+ t.plan(3);
var src = '(' + function () {
var sum = 0;
@@ -18,6 +18,9 @@ test('for loop', function (t) {
t.equal(node.update.source(), 'i++');
node.update.update('i+=2');
}
+ if (node.type === 'UpdateExpression') {
+ t.equal(node.source(), 'i++');
+ }
});
var res = vm.runInNewContext(output);
Please sign in to comment.
Something went wrong with that request. Please try again.