You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Add arrow function syntax for inline functions (#27)
* Add arrow function support for inline functions
* Address code review feedback: bounds check and documentation
* Update documentation with arrow function syntax
Copy file name to clipboardExpand all lines: docs/syntax.md
+54Lines changed: 54 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -17,6 +17,7 @@ The parser accepts a pretty basic grammar. It's similar to normal JavaScript exp
17
17
| and | Left | Logical AND |
18
18
| or | Left | Logical OR |
19
19
| x ? y : z | Right | Ternary conditional (if x then y else z) |
20
+
| => | Right | Arrow function (e.g., x => x * 2) |
20
21
| = | Right | Variable assignment |
21
22
| ; | Left | Expression separator |
22
23
@@ -345,6 +346,59 @@ You can also define the functions inline:
345
346
filter(isEven(x) = x %2==0, [1, 2, 3, 4, 5])
346
347
```
347
348
349
+
### Arrow Functions
350
+
351
+
Arrow functions provide a concise syntax for inline functions, similar to JavaScript arrow functions. They are particularly useful when passing functions to higher-order functions like `map`, `filter`, and `fold`.
352
+
353
+
**Single parameter (no parentheses required):**
354
+
355
+
```js
356
+
map(x=> x *2, [1, 2, 3]) // [2, 4, 6]
357
+
filter(x=> x >2, [1, 2, 3, 4]) // [3, 4]
358
+
map(x=>x.name, users) // Extract property from objects
filter(x=> x >0 and x <10, numbers) // Using logical operators
397
+
map(x=> x >5?"high":"low", [3, 7, 2, 9]) // Using ternary operator
398
+
```
399
+
400
+
> **Note:** Arrow functions share the same `fndef` operator flag as traditional function definitions. If function definitions are disabled via parser options, arrow functions will also be disabled.
401
+
348
402
## Custom JavaScript Functions
349
403
350
404
If you need additional functions that aren't supported out of the box, you can easily add them in your own code. Instances of the `Parser` class have a property called `functions` that's simply an object with all the functions that are in scope. You can add, replace, or delete any of the properties to customize what's available in the expressions. For example:
0 commit comments