Skip to content

Instantly share code, notes, and snippets.

@teckliew
Last active October 8, 2015 20:01
Show Gist options
  • Save teckliew/1a2335198237eebc7c9a to your computer and use it in GitHub Desktop.
Save teckliew/1a2335198237eebc7c9a to your computer and use it in GitHub Desktop.
alternatives to if's. if statement refactored.
//if statement
(if ( foo ) {
bar = "beta";
}
// and...
if ( foo ) {
bar();
})
//alternative
(foo && ( bar = "beta" );
// and...
foo && bar();
)
//if else
(if ( foo ) {
bar();
} else {
quux()
})
//aternative
// if foo is true, return bar(); if foo is false, bar() is skipped and false is returned
// for the left side and quux() is returned;
( foo && bar() ) || quux();
//alternative 2
foo ? bar() : quux();
//more complicated example adding numbers
if ( foo.length === 1 ) {
return parseInt( foo[0], 10 );
} else if ( foo.length === 2 ) {
return parseInt( foo[0], 10 ) + parseInt( foo[1], 10 );
} else if ( foo.length === 3 ) {
return parseInt( foo[0], 10 ) + parseInt( foo[1], 10 ) + parseInt( foo[2], 10 );
} else {
return 0;
}
//refactor
//parse all the numbers in the array and add
var ret = foo.map(function( val ) {
return parseInt( val, 10 );
}).join("+");
return ( ret && new Function("return " + ret )() ) || 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment