Last active
August 29, 2015 14:15
-
-
Save chocolateboy/67226b9bc0c948c1f1de to your computer and use it in GitHub Desktop.
sweet.js version of Groovy's Elvis operator
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
// 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