Possible bug in website - extremely strange!

Possible bug in website - extremely strange!
0.0 0

#1

I’m trying to solve this algorithm problem.

I’m pretty sure my code is correct, but it won’t let me pass the last test example. If I do a console.log for the output, sure enough, each test returns the correct answer except the last one. However, here’s the really weird part: if I copy/paste my code into Chrome’s dev console, it returns the correct answer for the last test. Any idea what’s going on? Here is my code:

function smallestCommons(arr) {
  let counter = 0;
  let found = false;
  
  //sort array
  arr.sort((a, b) => {return a - b;});

  //add missing numbers
  for(let i = arr[0]+1; i < arr[1]; i++){
    arr.push(i);
  }
  
  //sort again
  arr.sort((a, b) => {return a - b;});
  counter = Math.max(...arr);
  

  while(found === false){
    let i = 0;  
    while(i < arr.length){
      if(counter % arr[i] !== 0){
        break;
      }
      i++;
    }
    if(i === arr.length){
       found = true;
       break;
    }
    counter++;
  }
 console.log(counter);
  return counter;
}

#2

Everyone always assumes the code is broken. [rolls eyes] [wink]

But seriously, your code works. It’s just that it’s making the app nervous.

If you go into the code window and go to the bottom line, and change the test code to:

smallestCommons([23,18]);

You can see a response in the fake console:

Error: Potential infinite loop at line 20. To disable loop protection, write:
// noprotect
as the first line. Beware that if you do have an infinite loop in your code this will crash your browser.

If you put

// noprotect

as the first line, your code passes. It was just getting nervous about those while statements.

It’s not broken code, it’s a safety device to help prevent learning coders from locking up their browser.


#3

Looking at your code real quick,

while(found === false){

would usually be rendered as

while(!found ){

and, is there a reason why this:

    let i = 0;  
    while(i < arr.length){
      if(counter % arr[i] !== 0){
        break;
      }
      i++;
    }

isn’t a for loop?

    let i;
    for (i = 0;  i < arr.length; i++){
      if(counter % arr[i] !== 0)
        break;
    }

I guess it doesn’t have to be a for loop, but I think it’s more intuitive that way. I look at that and I instantly know what is happening. I always want my code to be as understandable to other coders and possible.


#4

Actually, there’s a nice array prototype method findIndex that could do it (the for loop) as well, but I’ll let you figure that out. I’m rambling, time for bed.


#5

Much appreciated! I was seeing that warning so often that I stopped paying attention to it.

And thanks for the factoring suggestions. I still have a while before I fully internalize the common sense stuff so my code tends to be pretty wonky. :slight_smile: