Skip to content

Commit 290705b

Browse files
aenglVitaly Puzrin
authored andcommitted
Support arrow functions without a block statement (#421)
1 parent bab69b5 commit 290705b

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

lib/js-yaml/type/js/function.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,14 @@ function constructJavascriptFunction(data) {
6565

6666
// Esprima's ranges include the first '{' and the last '}' characters on
6767
// function expressions. So cut them out.
68+
if (ast.body[0].expression.body.type === 'BlockStatement') {
69+
/*eslint-disable no-new-func*/
70+
return new Function(params, source.slice(body[0] + 1, body[1] - 1));
71+
}
72+
// ES6 arrow functions can omit the BlockStatement. In that case, just return
73+
// the body.
6874
/*eslint-disable no-new-func*/
69-
return new Function(params, source.slice(body[0] + 1, body[1] - 1));
75+
return new Function(params, 'return ' + source.slice(body[0], body[1]));
7076
}
7177

7278
function representJavascriptFunction(object /*, style*/) {

test/samples-common/construct-javascript-function.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ testHandler.expected = [
3131
function () {
3232
return 72;
3333
},
34+
function () {
35+
return 23;
36+
},
3437
function (x, y) {
3538
return x + y;
3639
},

test/samples-common/construct-javascript-function.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
- !!js/function 'function () { return 42 }'
22
- !!js/function '() => { return 72 }'
3+
- !!js/function '() => 23'
34
- !!js/function 'function (x, y) { return x + y; } '
45
- !!js/function |
56
function (foo) {

0 commit comments

Comments
 (0)