Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Last active February 14, 2019 06:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/6718f48295b285cf39ec to your computer and use it in GitHub Desktop.
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).
// 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 ] )
}
// 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