I have a simple function that has to give a change. Something like vending machine. It takes 2 arguments: price of the item and an array of bills and coins received. The output must be an array of numbers only in [quarter, dime, nickel, penny] format. For example, item costs 3.29 and the amount received is [1,1,2]. In this case the output must be [2,2,0,1] because the change which is 0.71 can be divided as 2 quarters, 2 dimes, 0 nickels and 1 penny. If amount received is less than a price then it has to return the full amount but only in format mentioned above. For example, if the price is 5 but amount paid is [2,2], the output must be [16,0,0,0]. I have created this function:
`function change(price,paid) {
const totalPaidVal = paid.reduce((a,b)=>a+b,0)
if (totalPaidVal === price) {
return(Array(4).fill(0))
} else if (price > totalPaidVal) {
const qNum = Math.floor(totalPaidVal/0.25);
const dNum = Math.floor((totalPaidVal-(qNum*0.25))/0.1);
const nNum = Math.floor((totalPaidVal-(qNum*0.25)-(dNum*0.1))/0.05);
const pNum = Math.round((totalPaidVal-(qNum*0.25)-(dNum*0.1)-(nNum*0.05))/0.01);
const arr = [qNum,dNum,nNum,pNum];
return arr;
} else if(price<totalPaidVal) {
const change = totalPaidVal-price;
const qNum = Math.floor(change/0.25);
const dNum = Math.floor((change-(qNum*0.25))/0.1);
const nNum = Math.floor((change-(qNum*0.25)-(dNum*0.1))/0.05);
const pNum = Math.round((change-(qNum*0.25)-(dNum*0.1)-(nNum*0.05))/0.01);
const arr = [qNum,dNum,nNum,pNum];
return arr;
}
}`
It works fine but I know that it looks like I repeat myself over again what is not good. I've been trying to create other variables to clean it up but it still looks pretty weird. There must be more efficient way to do that without repeating same pieces of code all the time. So, here is the question: what is the best way to clean it up and make it look simpler than now?