gkz / grasp

JavaScript structural search, replace, and refactor
http://graspjs.com
MIT License
1.28k stars 33 forks source link

question: reorder dependencies in define call #49

Closed ptbrowne closed 9 years ago

ptbrowne commented 9 years ago

Hi,

I am using requirejs for my project and I would like to know if grasp would be suitable to do the reordering of the arguments according to a specified order.

Background:

requirejs's define works like this:

define([depA, depB, depC], function (a,b,c) {
});

I want to reorder the arguments according to a function of my choosing, giving priorities: jQuery, underscore etc.. first, then my Backbone views, then my Backbone models and then all the other modules. My views and models are respectfully in views/ and models/ so I can match the path of the module to know its priority.

I guess the priority giving function would look something like:

var priorities = [
  'jquery',
  'underscore',
  'views/',
  'models/',
];
var enumPriorities = _.map(priorities, function (v, k) { return [k,v]; });
function priority (path) {
  return _.find(enumPriorities, function (o) {
     return o[1].match(path);
  })[0];
}

So the input would be

define(['models/hello', 'jquery', 'views/toto', 'underscore'], function (hello, $, toto, _) {
});

and the output

define(['jquery', 'underscore', 'views/toto', 'models/hello'], function ($, _, toto, hello) {
});

It seems that grasp cannot handle complex cases like this where the reordering is dynamic. Or can it ?

If Grasp cannot do it, what tool would you recommend ?

Thanks !

ptbrowne commented 9 years ago

I tried with esprima and escodegen and I managed to do what I wanted. Now I guess I have to manage to do it and leaving the other lines undisturbed. I think I am going to try with recast (https://github.com/benjamn/recast).

https://github.com/ptbrowne/ast/blob/master/tasks/reordering-define.js