Created
September 20, 2012 17:42
-
-
Save rmurphey/3757294 to your computer and use it in GitHub Desktop.
Reduce the Complexity of a Function
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
// a function that does too many things | |
function showPrice(row, standardPrice, discountPrice, savings, isProrated, isDeferred) { | |
var priceCol = row.find('td.price').eq(0); | |
var discountCol = row.find('td.price').eq(1); | |
var txt = ''; | |
if (!discountPrice && !standardPrice && !savings && !isProrated && !isDeferred) { | |
discountCol.html('<img src="/img/loading.gif" />'); | |
} else { | |
if (discountPrice && (standardPrice == discountPrice)) { | |
priceCol.html(''); | |
} else { | |
priceCol.html('<del>' + standardPrice + '</del>'); | |
} | |
txt = '<strong>'; | |
if (discountPrice == '$0.00') { | |
txt += 'FREE!'; | |
} | |
if (isProrated) { | |
txt += '*'; | |
} else if (isDeferred) { | |
txt += '**'; | |
} | |
txt += '</strong>'; | |
} | |
discountCol.html(txt); | |
} | |
showPrice(row, null, null, null, null, null); |
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
// sane-er code | |
var priceInfo = { | |
isProrated: true | |
}; | |
var priceHtml = getPrice(priceInfo); | |
var discountHtml = getDiscount(priceInfo); | |
updateRow(row, priceHtml, discountHtml); | |
function getDiscount(priceInfo) { | |
var txt; | |
if (priceInfo.discountPrice && priceInfo.standardPrice && priceInfo.savings && priceInfo.isProrated && priceInfo.isDeferred) { | |
if (priceInfo.discountPrice == '$0.00') { | |
txt += 'FREE!'; | |
} | |
if (priceInfo.isProrated) { | |
txt += '*'; | |
} else if (priceInfo.isDeferred) { | |
txt += '**'; | |
} | |
return '<strong>' + txt + '</strong>'; | |
} | |
return '<img src="/img/loading.gif" />'; | |
} | |
function getPrice(priceInfo) { | |
if (!priceInfo.standardPrice) { | |
return ''; | |
} | |
if (priceInfo.standardPrice == priceInfo.discountPrice) { | |
return ''; | |
} | |
return '<del>' + priceInfo.standardPrice + '</del>'; | |
} | |
function updateRow(row, priceHtml, discountHtml) { | |
row.find('td.price').eq(0).html(priceHtml); | |
row.find('td.price').eq(1).html(discountHtml); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment