Recreate Lodash - chunk() using a while loop

Continuing the discussion from Re-create Lodash Library - chunk() method:

hello! the instructions for recreating Lodash library’s chunk() method say that we can’t use a while loop because it can’t auto-increment. i wrote this method using a while loop like this, and it seems to pass the test… is there anything wrong with it, or a reason why i wouldn’t want to use it like this?

chunk(arr, size) {
    if (size === undefined) {
      size = 1;
    };
    let chunkedArr = [];
    let i = 0;
    while (i <= arr.length - 1) {
      let chunk = arr.slice(i, i + size);
      chunkedArr.push(chunk);
      i += size
    };
    return chunkedArr;
  }

thanks!

I believe CC means that there has to be extra code in order for to work:

and

If you had this in a for loop, you could compress these lines into one line:

for (let i = 0; i < arr.length - 1; i ++)

We managed to get the same code, but put it into one line.
Also, by this:

I think it means that you have to add a variableToIncrement += 1 in the code, whereas in the for loop, the loop auto increments by means of the variableToIncrement ++ inside the paranthesis.

I hope this helps!

okay that’s fair enough, thanks for taking the time!

1 Like