Last active
February 14, 2019 06:15
-
-
Save barneycarroll/6718f48295b285cf39ec to your computer and use it in GitHub Desktop.
A ternary function for convenient conditional expressions (especially in Mithril views, where ternary operators can look confusing).
This file contains 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
// Verbose ternary function to add debugging points and make views more legible. | |
// If `defer` is true and the pass/fail outcome is a function, it will be invoked: | |
// This allows you to conditionally return expressions which would break execution depending on `condition` | |
function tern( condition, pass, fail, defer ){ | |
if( !fail ) fail = '' | |
if( defer && condition instanceof Function ) condition = condition() | |
var outcome = condition ? pass : fail; | |
return defer && outcome instanceof Function ? outcome() : outcome | |
} | |
// Shorthand | |
tern.defer = function( x, y, z ){ | |
return tern.apply( undefined, [ x, y, z, true ] ) | |
} |
This file contains 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
// Verbose ternary function to add debugging points and make views more legible. | |
// If `defer` is true and the pass/fail outcome is a function, it will be invoked: | |
// This allows you to conditionally return expressions which would break execution depending on `condition` | |
function tern( condition, pass, fail='', defer=false ){ | |
if( defer && condition instanceof Function ) condition = condition() | |
var outcome = condition ? pass : fail | |
return defer && outcome instanceof Function ? outcome() : outcome | |
} | |
// Shorthand | |
tern.defer = ( ...args ) => tern( ...args, true ) | |
export default tern |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment