Skip to content

Instantly share code, notes, and snippets.

@kentaromiura
Created July 26, 2015 16:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kentaromiura/ecaa0ffcb116d60d789e to your computer and use it in GitHub Desktop.
Save kentaromiura/ecaa0ffcb116d60d789e to your computer and use it in GitHub Desktop.
MooTools Class to ES 2015
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
Copy link
Author

TODO:
1 - Implements,
2 - super call must be before any this. (@cpojer has a script to detect this)
3 - ???
4 - Profit!

@SergioCrisostomo
Copy link

SergioCrisostomo commented Jun 3, 2016

@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