DEV Community

Discussion on: JavaScript Challenge 3: Remove Zeroes

Collapse
 
mellen profile image
Matt Ellen • Edited

OK, you beat me this time! :D You're about 3x faster

Swapping the toString()s for two comparisons speeds it up a bit, but it still takes more than double the amount of time yours does.

Removing the call to swap (but still swapping) makes them pretty much identical. I had no idea a function call could be so heavy.

Collapse
 
mellen profile image
Matt Ellen
function put0AtTheBack(arr)
{
  let zeroIndex = -1;
  for(let i = 0; i < arr.length; i++)
  {
    let item = arr[i];
    if(item !== '0' && item !== 0 && zeroIndex !== -1)
    {
        let tmp = arr[i];
        arr[i] = arr[zeroIndex];
        arr[zeroIndex] = tmp;
        zeroIndex++;
    }

    if((item === '0' || item === 0) && zeroIndex === -1)
    {
        zeroIndex = i;
    }
  }
}
Collapse
 
albertomontalesi profile image
AlbertoM

That's an interesting find, I also wasn't aware that a function call would have made it that much worse.

Thread Thread
 
mellen profile image
Matt Ellen

Well, to be fair, that's over 100000 iterations. But surprising none-the-less.