Grab the first 4 items that meet the condition from a data set with an unknown size I was turned down for a job after a coding take-home test, and some of the feedback I received was:


  would have preferred to see more functional programming instead of
   while loops - and the while loops that were implemented weren't ideal.


Here is the while loop (there was only one) in question:

getDetails (id) {

    return this.$http.get(this.baseUrl + (this.detailPath.replace('{ID}', id)))
    .then((json) =&gt; {

        let i = 0;
        let result = [];
        while (i &lt; json.data.length &amp;&amp; result.length &lt; 4) {

            if (json.data[i].profile_path) {

                result.push(json.data[i]);

            }
            i++;

        }
        return result;

    });

}


I actually considered using a reducer function instead of the while loop, but there is no way to break out of the reducer once the result length condition (i.e. result.length &lt; 4) is no longer true. So that would mean that very large datasets would increase computation time. I created a jsperf to test this theory.

So, my question is this: am I missing something here? Is there a better, more efficient way to do this that I am overlooking?
So that would mean that very large datasets would increase computation time. 


You should ask if very large datasets are possible.  Because if they're not, clean code takes precedence over what would be a premature optimization.  All the code inside your then block can be replaced with a single line:

json.data.filter(x =&gt; x.profile_path).slice(0, 4)


If performance is truly an issue, your basic thinking is correct, but I'd just use a for loop:

let result = [];
let data = json.data
for (var i = 0; i &lt; data.length; i++) {
  if (data[i].profile_path) result.push(data[i])
  if (result.length == 4) return result
}
// ask interviewer what the behavior should be for incomplete results...


Note that returning inside a for loop will exit the function immediately.

Fwiw, it sounds like the problem you faced was mostly about communication with the interviewer. Next time, politely probe them about what they're looking for, what their assumptions are about the problem, and so on.