Last updated 2 years ago by Tan Li Hau
javascriptFollowing my previous post on writing a custom babel transformation, today I am going to show you how you can create a custom JavaScript syntax with Babel.
Let me show you what we will achieve at the end of this article:
language-js
// '@@' makes the function `foo` curried
function @@ foo(a, b, c) {
return a + b + c;
}
console.log(foo(1, 2)(3)); // 6
We are going to create a curry function syntax @@
. The syntax is like the generator function, except you place @@
instead of *
in between the function
keyword and the function name, eg function @@ name(arg1, arg2)
.
In this example, you can have partial application with the function foo
. Calling foo
with the number of parameters less than the arguments required will return a new function of the remaining arguments:
```language-js foo(1, 2, 3); // 6
const bar = foo(1, 2); // (n) => 1 + 2 + n bar(3); // 6 ```
The reason I choose
@@
is that you can’t have@
in a variable name, sofunction@@foo(){}
is still a valid syntax. And the “operator”@
is used for decorator functions but I wanted to use something entirely new, thus@@
.
To achieve this, we are going to:
Sounds impossible 😨?