Search code examples
javascriptfunctionmacroscoffeescripthoisting

coffeescript macro for function declarations


Functions in Coffeescript can't be hoisted, since it doesn't function declarations, only function expressions. How can I write a macro to add function declarations to coffeescript?

Specifically, I want:

foo(bar, baz) ->

to compile to:

function foo(bar, baz) {
}

instead of:

foo(bar, baz)(function() {});

Solution

  • I don't think you can do that unless you want to write foo in JavaScript and embed it in your CoffeeScript using backticks. For example:

    console.log f 'x'
    `function f(x) { return x }`
    

    becomes this JavaScript:

    console.log(f('x'));
    function f(x) { return x };
    

    and f will be executed as desired.

    If you want to change how CoffeeScript interprets foo(bar, baz) -> then you'll have to edit the parser and deal with all the side effects and broken code. The result will be something similar to CoffeeScript but it won't be CoffeeScript.

    CoffeeScript and JavaScript are different languages, trying to write CoffeeScript while you're thinking in JavaScript terms will just make a mess of things; they share a lot and CoffeeScript is compiled/translated to JavaScript but they're not the same language so you work with them differently. Don't write C code in C++, don't write Java in Scala, don't write JavaScript in CoffeeScript, ...