Skip to content

Instantly share code, notes, and snippets.

@barneycarroll barneycarroll/tern.es5.js
Last active Feb 14, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.