NeilFraser / JS-Interpreter

A sandboxed JavaScript interpreter in JavaScript.
Apache License 2.0
1.98k stars 353 forks source link

Support for arrow functions #206

Closed bjrne closed 3 years ago

bjrne commented 3 years ago

I could not find an issue regarding arrow functions so far, so I hope this is the right place and no duplicate. As a lot of Javascript example code works with functions using the arrow syntax, I was surprised to find out that this interpreter does not seem to be able to handle these. Example that you can paste into the live demo:

// works:
alert((function(x){return x})(3));
// does not work:
alert((x => x)(3));

For my purposes I can use the longer variant, but it would be pretty neat if the shorter syntax was supported. At least a hint in the docs or a list of supportedd features would be very much appreciated. Thanks for the nice project!

NeilFraser commented 3 years ago

Arrow functions are a feature of ES6. See issue #186.

raymonable commented 1 year ago

I've written a transpiler specifically for arrow functions, and it simply converts them into regular functions. Hope this helps!

var _ = "() => {}"
var [__, ___] = [(/\s*\)\s*=\s*>\s*{/g)];
var ____ = [];
while (___ = __.exec(_)) {
    let __ = ___.index;
    while (_.substring(__, __ + 1) !== "(" || __ <= 0) {
        __ -= 1;
    }
    ____.push(__)
};
var __ = 0;
____.forEach((index) => {
    __ += index;
    _ = _.substring(0, __) + 'function' + _.substring(__)
    __ += ('function').length - 1
})
_ = _.replace((/\s*\)\s*=\s*>\s*{/g), ') {');
console.log(_) // _ is the output.