Double Cola Challenge, JavaScript code wrong?
<p>Five friends are drinking magic cola in an line. When the first friend drinks the cola he disappears, and multiplies into two copies! After that, those new copies go to the end of the line and the next friend drinks the magic cola, repeating the proccess.</p>

<p>For example, imagine we have the following friends:</p>

<pre><code>[Sheldon, Leonard, Penny, Rajesh, Howard]
</code></pre>

<p>After Sheldon drinking the first cola, the line will look like this:</p>

<pre><code>[Leonard, Penny, Rajesh, Howard, Sheldon, Sheldon]
</code></pre>

<p>After Leonard drinking the cola, the line gets like this:</p>

<pre><code>[Penny, Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard]
</code></pre>

<p>And so on...</p>

<p>My objective is to write a function in JavaScript, that given an array with the names of the people in the line, and a number N, it will return the the name of the N-ith person drinking the magic cola.</p>

<p>So, for example, doing <code>console.log(whoIsNext([Sheldon, Leonard, Penny, Rajesh, Howard], 1))</code> should return <code>Sheldon</code>.</p>

<p>To achieve this, I made this code:</p>

<pre><code>function whoIsNext(names, r){
  var fistInLine;

  if(r &lt;= names.length){
    return names[r-1];
  }else{

    while(r &gt; names.length){
      fistInLine = names.shift();
      names.push(fistInLine, fistInLine);
    }
    return names[r-1];
  }
}
</code></pre>

<p>This function works well for the following case:</p>

<pre><code>names = ["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"];
Test.assertEquals(whoIsNext(names, 1), "Sheldon");
</code></pre>

<p>But it fails for the test:</p>

<pre><code>names = ["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"];
Test.assertEquals(whoIsNext(names, 52), "Penny");
</code></pre>

<p>And if I try with a really big number, like:</p>

<pre><code>names = ["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"];
Test.assertEquals(whoIsNext(names, 7230702951), "Leonard");
</code></pre>

<p>It doesn't even stop running (takes forever). </p>

<p>So obviously, my solution is not only incorrect, it seems to be inneficient as well. How can I fix it?</p>