Skip to content

Instantly share code, notes, and snippets.

@qerub
Forked from aaronpowell/null-guard.sjs
Created April 18, 2014 23:36
Show Gist options
  • Save qerub/11068592 to your computer and use it in GitHub Desktop.
Save qerub/11068592 to your computer and use it in GitHub Desktop.
The ?. operator from C# for JavaScript via Sweet.js
// This version allows LHS to be any expression
// (and makes sure it's only evaluated once by storing the result)
let (?.) = macro {
rule infix { $lhs:expr | $rhs:ident } => {
(function ($tmp) {
return $tmp === null ? null : $tmp.$rhs;
})($lhs)
}
}
function bar() {
return {
a: 'a',
baz: {
notB: 'not b'
}
};
}
var foo = bar()?.baz?.b;
console.log(foo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment