Skip to content

Instantly share code, notes, and snippets.

@ozten
Forked from disnet/gist:6024833
Created June 10, 2014 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozten/0a2e982044de8830f105 to your computer and use it in GitHub Desktop.
Save ozten/0a2e982044de8830f105 to your computer and use it in GitHub Desktop.
macro _match_cond {
rule {$o($field)} => {
(typeof $o.$field !== 'undefined')
}
rule {$o($field $rest...)} => {
_match_cond $o($field) && _match_cond $o($rest...)
}
}
macro _match_var {
rule {$o($field)} => {
var $field = $o.$field;
}
rule {$o($field $rest...)} => {
_match_var $o($field)
_match_var $o($rest...)
}
}
macro match {
rule {$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