Skip to content

Instantly share code, notes, and snippets.

@disnet
Last active December 19, 2015 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save disnet/6024833 to your computer and use it in GitHub Desktop.
Save disnet/6024833 to your computer and use it in GitHub Desktop.
simple object structure case matching macro
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