Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Jul 26, 2015

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

@SergioCrisostomo

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.