Last active
December 19, 2015 22:08
-
-
Save disnet/6024833 to your computer and use it in GitHub Desktop.
simple object structure case matching macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
macro _match_cond { | |
case $o ($field) => { | |
(typeof $o.$field !== 'undefined') | |
} | |
case $o ($field $rest ...) => { | |
_match_cond $o ($field) && _match_cond $o ($rest ...) | |
} | |
} | |
macro _match_var { | |
case $o ($field) => { | |
var $field = $o.$field; | |
} | |
case $o ($field $rest ...) => { | |
_match_var $o ($field) | |
_match_var $o ($rest ...) | |
} | |
} | |
macro match { | |
case $tomatch:expr { | |
$({$field:ident (,) ...} => { $body ... }) ... | |
} => { | |
var obj = $tomatch; | |
$(if (_match_cond obj ($field ...)) { | |
_match_var obj ($field ... ) | |
$body ... | |
}) ... | |
} | |
} | |
match { id: "myid", foo: 42 } { | |
{id, foo} => { | |
log(id); | |
log(foo + 24); | |
} | |
{id} => { | |
log(id) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment