Skip to content

Instantly share code, notes, and snippets.

@redbar0n
Last active December 27, 2020 14:54
Show Gist options
  • Save redbar0n/e211f86c142d87810f850de668da5256 to your computer and use it in GitHub Desktop.
Save redbar0n/e211f86c142d87810f850de668da5256 to your computer and use it in GitHub Desktop.
Do not comment the self-evident.
// ---
// The following code is from: https://github.com/dwyl/learn-tdd/blob/master/change.js
// Note that:
// - The JsDoc mentioning the params to getChange became out of sync after it apparently was refactored. Therefore, avoid such comments.
// - There are quite a few comments merely detailing what can be self-evidently / obviously read from the code itself. They don't reveal anything more (like intent/purpose) than the code itself, and just add noise, and can become out of sync, so avoid those.
var coins = [200, 100, 50, 20, 10, 5, 2, 1];
/**
* getChange accepts two parameters (totalPayable and cashPaid) and calculates
* the change in "coins" that needs to be returned.
* @param {number} payable the integer amount (in pennies) payable (to be paid)
* @param {number} paid the integer amount (in pennies) the person paid
* @returns {array} change the list of coins we need to dispense to the person
* @example
* getChange(215, 300); // returns [50, 20, 10, 5]
*/
function getChange (payable, paid) {
var change = [];
var length = coins.length;
var remaining = paid - payable; // we reduce this below
for (var i = 0; i < length; i++) { // loop through array of notes & coins:
var coin = coins[i];
var times_coin_fits = Math.floor(remaining / coin); // no partial coins
if(times_coin_fits >= 1) { // check coin fits into the remaining amount
for(var j = 0; j < times_coin_fits ; j++) { // add coin to change x times
change.push(coin);
remaining = remaining - coin; // subtract coin from remaining
}
}
}
return change;
};
// ---
// The following code is kept the same code as the code above (for easy comparison), but with self-evident comments removed (plus improved JsDoc):
var coins = [200, 100, 50, 20, 10, 5, 2, 1];
/**
* getChange returns the left over amount after payment, as a list of the actual coins.
* @param {number} payable the integer amount (in pennies) payable (to be paid)
* @param {number} paid the integer amount (in pennies) the person paid
* @returns {array} change the list of coins we need to dispense to the person
* @example
* getChange(215, 300); // returns [50, 20, 10, 5]
*/
function getChange (payable, paid) {
var change = [];
var length = coins.length;
var remaining = paid - payable;
for (var i = 0; i < length; i++) {
var coin = coins[i];
var times_coin_fits = Math.floor(remaining / coin);
if(times_coin_fits >= 1) {
for(var j = 0; j < times_coin_fits ; j++) {
change.push(coin);
remaining = remaining - coin;
}
}
}
return change;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment