Skip to content

Instantly share code, notes, and snippets.

@adyngom
Created July 1, 2019 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adyngom/3bbe89d657ce2f6319e035dc31122907 to your computer and use it in GitHub Desktop.
Save adyngom/3bbe89d657ce2f6319e035dc31122907 to your computer and use it in GitHub Desktop.
Solution to rolls of coins workshop - JavaScript Alpharetta June 2019
const coinsJar = [5, 10, 10, 25, 25, 25, 10, 5, 1, 1, 1, 25, 25];
// [...coinsJar].forEach
const coinRolls = { "1": 2, "5": 2, "10": 2, "25": 2 };
const coinsLabels = {
"1": "Pennies",
"5": "Nickels",
"10": "Dimes",
"25": "Quarters"
};
const coinsCount = coinsJar.reduce(groupBy, {});
//console.log(coinsCount);
const coinsInfo = Object.keys(coinsCount).map(key => {
const totalCoins = coinsCount[key];
const rollCount = coinRolls[key];
const label = coinsLabels[key];
const { quotient, remainder } = getQuotientRemainder(totalCoins, rollCount);
const coinInfo = { label, quotient, remainder };
return coinInfo;
});
//console.log(coinsInfo);
console.log(coinsInfo.map(displayRollMessage).join("\n"));
function groupBy(bag, coins) {
!!bag[coins] ? (bag[coins] += 1) : (bag[coins] = 1);
return { ...bag };
}
function getQuotientRemainder(x, y) {
if (!y) {
/// throw error
}
return { quotient: parseInt(x / y), remainder: x % y };
}
function displayRollMessage(info) {
const { label, quotient: rolls, remainder: left } = info;
return `${label}: ${rolls} rolls - ${left} left`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment