Created
July 26, 2015 16:43
-
-
Save kentaromiura/ecaa0ffcb116d60d789e to your computer and use it in GitHub Desktop.
MooTools Class to ES 2015
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function(file, api) { | |
var j = api.jscodeshift; | |
var root = j(file.source); | |
root.find(j.Identifier).forEach(function(p) { | |
if(p.value.name === 'Class') { | |
if(p.parentPath.name === 'init'){ | |
var classDefinition = p.parentPath.value.arguments[0]; | |
var varname = p.parentPath.parentPath; | |
var name = varname.value.id; | |
var target = varname.parentPath.parentPath | |
var Extends = null; | |
var methods = classDefinition.properties.map((prop) => { | |
var name = prop.key.name | |
if (name === 'initialize') name = 'constructor'; | |
if (name === 'Extends') { | |
Extends = j.identifier(prop.value.name); | |
return {} | |
} | |
// TODO: Implements | |
var body = prop.value.body; | |
j(body).find(j.MemberExpression).forEach((calls)=>{ | |
if(calls.value.property.name === 'parent'){ | |
j(calls).replaceWith(j.identifier('super')) | |
} | |
}) | |
return {name, [name]:body, params:prop.value.params} | |
}) | |
var definition = []; | |
for(var method of methods){ | |
if(method.name) | |
definition.push(j.methodDefinition('init', | |
j.identifier(method.name), | |
j.functionExpression(null, method.params, method[method.name]) | |
)); | |
} | |
var substituteClass = j.classDeclaration(name, j.classBody(definition), Extends) | |
j(target).replaceWith(substituteClass); | |
} | |
} | |
}); | |
return root.toSource(); | |
}; |
@kentaromiura: What should be the output of this?
var Widget = new Class({
Implements: Options,
options: {
color: '#fff',
size: {
width: 100,
height: 100
}
},
initialize: function(options){
this.setOptions(options);
}
});
A:
class _Widget {
constructor(config) {
this.Implement(config.Implements);
this.setOptions(config.options);
}
}
var Widget = new _Widget({etc...});
B:
var Widget = new class {
constructor(options, Implements) {
this.Implement(Implements);
this.setOptions(options);
return this;
}
}({etc...});
or something else?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO:
1 - Implements,
2 - super call must be before any
this.
(@cpojer has a script to detect this)3 - ???
4 - Profit!