Permalink
Browse files

.parent test passes

  • Loading branch information...
1 parent 73ff250 commit ad43de54c16f6c98ac71a72db52c7966fb780a84 @substack committed Apr 28, 2012
Showing with 21 additions and 14 deletions.
  1. +12 −7 index.js
  2. +9 −7 test/parent.js
View
@@ -7,8 +7,11 @@ module.exports = function (src, fn) {
var output = src.split('');
var index = 0;
- function insertHelpers (node) {
+ function insertHelpers (node, parent) {
if (!node.range) return;
+
+ node.parent = parent;
+
node.source = function () {
return output.slice(node.range[0], node.range[1] + 1).join('');
};
@@ -21,25 +24,27 @@ module.exports = function (src, fn) {
};
}
- (function walk (node) {
- insertHelpers(node);
+ (function walk (node, parent) {
+ insertHelpers(node, parent);
Object.keys(node).forEach(function (key) {
+ if (key === 'parent') return;
+
var child = node[key];
if (Array.isArray(child)) {
child.forEach(function (c) {
if (c && typeof c === 'object' && c.type) {
- walk(c);
+ walk(c, node);
}
});
}
else if (child && typeof child === 'object' && child.type) {
- insertHelpers(child);
- walk(child);
+ insertHelpers(child, node);
+ walk(child, node);
}
});
fn(node);
- })(ast);
+ })(ast, undefined);
return output.join('');
};
View
@@ -3,24 +3,26 @@ var test = require('tap').test;
var vm = require('vm');
test('parent', function (t) {
- t.plan(3);
+ t.plan(5);
var src = '(' + function () {
var xs = [ 1, 2, 3 ];
- fn(xs);
+ fn(ys);
} + ')()';
var output = falafel(src, function (node) {
if (node.type === 'ArrayExpression') {
- t.equal(node.parent.type, 'VariableDeclaration');
- t.equal(node.parent.source(), 'var xs = [ 1, 2, 3 ];');
- node.parent.update('var xs = 4;');
+ t.equal(node.parent.type, 'VariableDeclarator');
+ t.equal(node.parent.source(), 'xs = [ 1, 2, 3 ]');
+ t.equal(node.parent.parent.type, 'VariableDeclaration');
+ t.equal(node.parent.parent.source(), 'var xs = [ 1, 2, 3 ];');
+ node.parent.update('ys = 4;');
}
});
vm.runInNewContext(output, {
- fn : function (xs) {
- t.equal(xs, 4);
+ fn : function (x) {
+ t.equal(x, 4);
},
});
});

0 comments on commit ad43de5

Please sign in to comment.