Increasing number by 1 crashes code editor

I’m writing a cash register function that breaks down change into smallest possible denominations by comparing it to the denominations array. So 8.55 becomes array
[8, 0.5, 0.05] which breaks down into [5, 3, 0.5, 0.05] but as soon as I go above 10 the editor crashes. Even though 14.55 for example should simply be broken down as [10, 4, 0.5, 0.05]. What am I missing?

let change = [8, 0.9, 0.06]
let denom = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100]
for (let x of change) {
    for (let y of denom) {
        if (x / y > 1 && x / y < 4) {
        let mlt = Math.floor(x / y)
        largestFit = y * mlt
        let idx = change.indexOf(x)
        change.splice(idx, 1, largestFit)
        change.splice(idx + 1, 0, x - largestFit)
        }
    }
}
change = change.map(a => Number(a.toFixed(2))).filter(a => a > 0)
console.log(change)

It is not above 10 that your code has a problem, it is greater or equal to 11.

Your change array grows infinitely large when you attempt to use anything greater or equal to [11, 0, 0] .

I gave up on trying to understand your algorithm, but I did add some console.log statements and a way to break out of the loops after the if statement evaluates to true after 10 times, so you can see that your algorithm is causing change to keep growing.

splice mutates the original array and sometimes (like this) can make it difficult to debug what is going on.

You will probably want to add a few more console.log statements to figure out exactly where your logic breaks down.

function changeit() {
  let change = [11, 0, 0]
  let denom = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100]
  let count = 0;
  for (let x of change) {
    console.log('x='+x)
    for (let y of denom) {
      console.log('y='+y)
      if (x / y > 1 && x / y < 4) {
        let mlt = Math.floor(x / y)
        largestFit = y * mlt
        let idx = change.indexOf(x)
        console.log('count=' + ++count);
        change.splice(idx, 1, largestFit)
        console.log(change);

        change.splice(idx + 1, 0, x - largestFit)
        console.log(change)
        if (count >= 10) {
          return change;
        }
      }
    }
  }

  change = change.map(a => Number(a.toFixed(2))).filter(a => a > 0)
  return change;
}

changeit()
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.