Hacker News new | past | comments | ask | show | jobs | submit login

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



That'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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: