Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

initial array transformation seems to work

  • Loading branch information...
commit c90401de88a0929eabb7fd2b4066726a6e85edb1 0 parents
@substack authored
Showing with 62 additions and 0 deletions.
  1. +16 −0 example/array.js
  2. +46 −0 index.js
16 example/array.js
@@ -0,0 +1,16 @@
+var falafel = require('../');
+
+var src = '(' + function () {
+ var xs = [ 1, 2, [ 3, 4 ] ];
+ var ys = [ 5, 6 ];
+ console.dir([ xs, ys ]);
+} + ')()';
+
+var output = falafel(src, function (node) {
+ if (node.type === 'ArrayExpression') {
+ node.update(function (s) {
+ return 'fn(' + s + ')';
+ });
+ }
+});
+console.log(output);
46 index.js
@@ -0,0 +1,46 @@
+var parse = require('esprima').parse;
+
+module.exports = function (src, fn) {
+ if (typeof src !== 'string') src = String(src);
+ var ast = parse(src, { range : true });
+
+ var output = src.split('');
+ var index = 0;
+
+ function insertUpdate (node) {
+ if (!node.range) return;
+ node.source = function () {
+ return output.slice(node.range[0], node.range[1] + 1).join('');
+ };
+
+ node.update = function (cb) {
+ var res = cb(node.source());
+ output[node.range[0]] = res;
+ for (var i = node.range[0] + 1; i < node.range[1] + 1; i++) {
+ output[i] = '';
+ }
+ };
+ }
+
+ (function walk (node) {
+ insertUpdate(node);
+
+ Object.keys(node).forEach(function (key) {
+ var child = node[key];
+ if (Array.isArray(child)) {
+ child.forEach(function (c) {
+ if (c && typeof c === 'object' && c.type) {
+ walk(c);
+ }
+ });
+ }
+ else if (child && typeof child === 'object' && child.type) {
+ insertUpdate(child);
+ walk(child);
+ }
+ });
+ fn(node);
+ })(ast);
+
+ return output.join('');
+};

0 comments on commit c90401d

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