3 ms·
Combining switch statements with destructuring [1] can be very useful: type ASTNode = { tag: 'BinOp', op: string, left: ASTNode, right: ASTNode }
by peterkelly 9y ago
Combining switch statements with destructuring [1] can be very useful:
type ASTNode = { tag: 'BinOp', op: string, left: ASTNode, right: ASTNode }
| { tag: 'UnaryOp', op: string, arg: ASTNode }
| { tag: 'Literal', value: number };
function evaluate(node: ASTNode): number {
switch (node.tag) {
case 'BinOp': { const { op, left, right } = node;
return evalBinary(op, evaluate(left), evaluate(right)); }
case 'UnaryOp': { const { op, arg } = node;
return evalUnary(op, evaluate(arg)); }
case 'Literal': { const { value } = node;
return value; }
}
}
[1] https://ponyfoo.com/articles/es6-destructuring-in-depth https://ponyfoo.com/articles/es6-destructuring-in-depth
- masklinn 9y agoThat's just sad if you've used languages with actual pattern matching though. It's like C's unsafe unions being back with a furor.