Skip to content

Instantly share code, notes, and snippets.

@rmurphey
Created September 20, 2012 17:42
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 rmurphey/3757294 to your computer and use it in GitHub Desktop.
Save rmurphey/3757294 to your computer and use it in GitHub Desktop.
Reduce the Complexity of a Function
// 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);
// 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