Skip to content

Instantly share code, notes, and snippets.

@AlphaGit
Created September 13, 2017 14:09
Show Gist options
  • Save AlphaGit/9395e3a8997e5b6694421824276c6084 to your computer and use it in GitHub Desktop.
Save AlphaGit/9395e3a8997e5b6694421824276c6084 to your computer and use it in GitHub Desktop.
Good code / bad code: good code
function checkoutCart(session) { // this is the code that executes on checkout
trackActivity(session, ACTIONS.CHECKED_OUT); // it tracks that the user is checking out
return getUserInfo(session.userId) // gets the user info with the user id
.then(user => getDiscountAmount(user)) // then it gets the discount for the user
.then(discAmt => addDiscountIfAny(session, discAmt)) // then it applies the discount
.then(getPaymentScreenConfig) // then it gets the payment screen configuration
.then(payScrCfg => new PaymentScreen(payScrCfg, session.cart)); // and it returns the payment screen
}
function getDiscountAmount(user) { // this is the code that gets the discount amount
if (user.hasDiscountedProfile) { // if the user has a profile for discounts
return retrieveDiscount(user.profileId); // it will retrieve that discount
} else { // otherwise (user has no discounts)
return 0; // discount amount is zero
}
}
function addDiscountIfAny(session, discAmt) { // here we apply discounts if applicable
if (discAmt > 0) { // if there is a discount amount
session.cart.addDiscount(discAmt); // we add it to the cart
}
}
@wzalazar
Copy link

wzalazar commented Sep 13, 2017

the conditional else is not necessary, just

function getDiscountAmount(user) {                                  
  if (user.hasDiscountedProfile) {                                 
    return retrieveDiscount(user.profileId);                  
  }                                                 
  return 0;                                                
}

more short

function getDiscountAmount(user) {   
   return user.hasDiscountedProfile ? retrieveDiscount(user.profileId) : 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment