Skip to content

Commit

Permalink
feat(literals): add support for default assignment for object destruc…
Browse files Browse the repository at this point in the history
…turing
  • Loading branch information
kollhof committed Feb 26, 2020
1 parent cef0576 commit 560c3fd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
31 changes: 28 additions & 3 deletions src/lang/literals/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,46 @@ const value_expr = (ctx, key)=> {
};


const default_assignment = (ctx, left)=> {
const expr_ctx = advance(ctx);

const [right, next_ctx] = expression(expr_ctx, 0);
const {loc: {end}} = right;

//TODO: assign and this func should use common code
return [
{type: 'assign', op: '=', left, right, loc: {...left.loc, end}},
next_ctx
];
};


const key_expr = (ctx)=> {
if (next_is(ctx, '`') || next_is(ctx, '...')) {
return expression(ctx, 0);
}

const key_ctx = advance(ctx);
const loc = curr_loc(key_ctx);
const key = {type: other_token, value: curr_value(key_ctx), loc};

if (next_is(key_ctx, '=')) {
return default_assignment(key_ctx, key);
}

return [{type: other_token, value: curr_value(key_ctx), loc}, key_ctx];
return [key, key_ctx];
};


const prop_expr = (ctx)=> {
const [key, value_ctx] = key_expr(ctx);
const [value, next_ctx] = value_expr(value_ctx, key);
const [key_or_default, value_ctx] = key_expr(ctx);
const [value, next_ctx] = value_expr(value_ctx, key_or_default);

const key = (
key_or_default.type === 'assign'
? key_or_default.left
:key_or_default
);

const {start} = key.loc;
const {end} = value.loc;
Expand Down
23 changes: 23 additions & 0 deletions src/lang/literals/object.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ describe('object {...}', ()=> {
});
});


it('parses single str prop: {`foo`: spam}', ()=> {
expect(
parse_expr('{`foo`: spam}')
Expand All @@ -115,6 +116,28 @@ describe('object {...}', ()=> {
}
});
});


it('parses default assignment prop: {foo=123}', ()=> {
expect(
parse_expr(`{foo=123}`)
).toEqual({
type: 'object',
props: [{
type: 'prop',
key: parse_expr(` foo`),
value: parse_expr(` foo=123`),
loc: {
start: {pos: 1, line: 1, column: 1},
end: {pos: 8, line: 1, column: 8}
}
}],
loc: {
start: {pos: 0, line: 1, column: 0},
end: {pos: 9, line: 1, column: 9}
}
});
});
});


Expand Down

0 comments on commit 560c3fd

Please sign in to comment.