Last active
July 15, 2016 06:57
-
-
Save deontologician/e65923823e0c3111c880 to your computer and use it in GitHub Desktop.
sweetjs reql macros
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 ? { | |
case infix { | |
$test:expr | _ $succeed:expr : $fail:expr | |
} => { | |
return #{r.branch($test, $succeed, $fail)} | |
} | |
} | |
operator (-) 12 left | |
{ $a, $b } => #{ r.expr($a).sub($b) } | |
operator (+) 12 left | |
{ $a, $b } => #{ r.expr($a).add($b) } | |
operator (*) 13 left | |
{ $a, $b } => #{ r.expr($a).mul($b) } | |
operator (%) 13 left | |
{ $a, $b } => #{ r.expr($a).mod($b) } | |
operator (==) 9 left | |
{ $a, $b } => #{ r.expr($a).eq($b) } | |
operator (!=) 9 left | |
{ $a, $b } => #{ r.expr($a).ne($b) } | |
operator (&&) 5 left | |
{ $a, $b } => #{ r.expr($a).and($b) } | |
operator (||) 4 left | |
{ $a, $b } => #{ r.expr($a).or($b) } | |
macro to_str { | |
case { _ ($toks ...) } => { | |
return [makeValue(#{ $toks ... }.map(unwrapSyntax).join('').toUpperCase(), #{ here })]; | |
} | |
} | |
macro instanceof { | |
case infix { | |
$a:expr | _ $b:ident | |
} => { | |
return #{ r.expr($a).typeOf().eq(to_str($b)) }; | |
} | |
} | |
operator ! 14 | |
{ $a } => #{ r.expr($a).not() } | |
operator (<) 10 left | |
{ $a, $b } => #{ r.expr($a).lt($b) } | |
operator (<=) 10 left | |
{ $a, $b } => #{ r.expr($a).le($b) } | |
operator (>) 10 left | |
{ $a, $b } => #{ r.expr($a).gt($b) } | |
operator (>=) 10 left | |
{ $a, $b } => #{ r.expr($a).ge($b) } | |
// Here's the query that gets converted: | |
r.table('foo').filter(function (x) { | |
return (x('bar') instanceof number) ? doc('baz') >= 23 : doc('baz') % 3 == 1; | |
}) | |
// Into the following: | |
r.table('foo').filter(function (x) { | |
return r.branch(r.expr(x('bar')).typeOf().eq('NUMBER'), r.expr(doc('baz')).ge(23), r.expr(r.expr(doc('baz')).mod(3)).eq(1)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment