Skip to content
This repository
Browse code

.parent test passes

  • Loading branch information...
commit ad43de54c16f6c98ac71a72db52c7966fb780a84 1 parent 73ff250
James Halliday authored

Showing 2 changed files with 21 additions and 14 deletions. Show diff stats Hide diff stats

  1. +12 7 index.js
  2. +9 7 test/parent.js
19 index.js
@@ -7,8 +7,11 @@ module.exports = function (src, fn) {
7 7 var output = src.split('');
8 8 var index = 0;
9 9
10   - function insertHelpers (node) {
  10 + function insertHelpers (node, parent) {
11 11 if (!node.range) return;
  12 +
  13 + node.parent = parent;
  14 +
12 15 node.source = function () {
13 16 return output.slice(node.range[0], node.range[1] + 1).join('');
14 17 };
@@ -21,25 +24,27 @@ module.exports = function (src, fn) {
21 24 };
22 25 }
23 26
24   - (function walk (node) {
25   - insertHelpers(node);
  27 + (function walk (node, parent) {
  28 + insertHelpers(node, parent);
26 29
27 30 Object.keys(node).forEach(function (key) {
  31 + if (key === 'parent') return;
  32 +
28 33 var child = node[key];
29 34 if (Array.isArray(child)) {
30 35 child.forEach(function (c) {
31 36 if (c && typeof c === 'object' && c.type) {
32   - walk(c);
  37 + walk(c, node);
33 38 }
34 39 });
35 40 }
36 41 else if (child && typeof child === 'object' && child.type) {
37   - insertHelpers(child);
38   - walk(child);
  42 + insertHelpers(child, node);
  43 + walk(child, node);
39 44 }
40 45 });
41 46 fn(node);
42   - })(ast);
  47 + })(ast, undefined);
43 48
44 49 return output.join('');
45 50 };
16 test/parent.js
@@ -3,24 +3,26 @@ var test = require('tap').test;
3 3 var vm = require('vm');
4 4
5 5 test('parent', function (t) {
6   - t.plan(3);
  6 + t.plan(5);
7 7
8 8 var src = '(' + function () {
9 9 var xs = [ 1, 2, 3 ];
10   - fn(xs);
  10 + fn(ys);
11 11 } + ')()';
12 12
13 13 var output = falafel(src, function (node) {
14 14 if (node.type === 'ArrayExpression') {
15   - t.equal(node.parent.type, 'VariableDeclaration');
16   - t.equal(node.parent.source(), 'var xs = [ 1, 2, 3 ];');
17   - node.parent.update('var xs = 4;');
  15 + t.equal(node.parent.type, 'VariableDeclarator');
  16 + t.equal(node.parent.source(), 'xs = [ 1, 2, 3 ]');
  17 + t.equal(node.parent.parent.type, 'VariableDeclaration');
  18 + t.equal(node.parent.parent.source(), 'var xs = [ 1, 2, 3 ];');
  19 + node.parent.update('ys = 4;');
18 20 }
19 21 });
20 22
21 23 vm.runInNewContext(output, {
22   - fn : function (xs) {
23   - t.equal(xs, 4);
  24 + fn : function (x) {
  25 + t.equal(x, 4);
24 26 },
25 27 });
26 28 });

0 comments on commit ad43de5

Please sign in to comment.
Something went wrong with that request. Please try again.