Skip to content

Instantly share code, notes, and snippets.

@marsgpl
Created March 19, 2019 17:28
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 marsgpl/16e63f04480a8e400cb84001b9149c19 to your computer and use it in GitHub Desktop.
Save marsgpl/16e63f04480a8e400cb84001b9149c19 to your computer and use it in GitHub Desktop.
var moneyTypes = [5000, 1000, 500, 100, 50, 30]
var lims = {
5000: 4,
1000: 5,
500: 2,
100: 5,
50: 100,
30: 23
}
function getMoney(amount, limits) {
const result = {}
for ( let value of moneyTypes ) {
result[value] = Math.floor(amount / value)
amount = amount % value
limits[value] -= result[value]
if ( limits[value] < 0 ) {
amount += Math.abs(limits[value]) * value
result[value] -= Math.abs(limits[value])
limits[value] = 0
}
}
if ( amount > 0 ) { throw new Error(`unable to provide requested sum: extra ${amount} RUR`) }
return {
res: result,
limits,
}
}
console.log(getMoney(21330, lims))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment