Skip to content

Instantly share code, notes, and snippets.

@chocolateboy
Last active August 29, 2015 14:15
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save chocolateboy/67226b9bc0c948c1f1de to your computer and use it in GitHub Desktop.
sweet.js version of Groovy's Elvis operator
// Groovy's Elvis operator
//
// lhs ?: rhs
//
// is equivalent to:
//
// lhs == null ? rhs : lhs
//
// or:
//
// (function ($lhs) { return $lhs == null ? rhs : $lhs })(lhs)
//
// depending on whether lhs has (or might have) side-effects
// (e.g. getters/proxies/expressions)
binaryop (?:) 4 right {
macro {
rule { (null) ($rhs:expr) } => { $rhs }
rule { (undefined) ($rhs:expr) } => { $rhs }
rule { ($lhs:lit) ($rhs:expr) } => { $lhs }
rule { ($lhs:ident) ($rhs:expr) } => {
($lhs == null ? $rhs : $lhs)
}
rule { ($lhs:expr) ($rhs:expr) } => {
(function(lhs) { return lhs == null ? $rhs : lhs }($lhs))
}
}
}
var foo = bar ? baz : quux;
var foo = bar ? baz ?: 42 : quux ?: 42;
var foo = undefined ?: undefined ?: 42;
var foo = null ?: null ?: 42;
var foo = undefined ?: null ?: 42;
var foo = null ?: undefined ?: 42;
var foo = foo ?: bar ?: baz;
var foo = '' ?: 0 ?: bar;
var foo = 0 ?: '' ?: bar;
var foo = foo.bar ?: foo.baz ?: foo.quux;
var foo = undefined ?: null ?: 0 ?: '' ?: foo ?: foo.bar;
var foo = foo.bar ?: foo ?: 0 ?: '' ?: null ?: undefined;
var foo = ++bar ?: ++baz;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment