Basic Algorithm Scripting - Chunky Monkey / Is this code "clean"?

Hi all,
the code works for the challenge, but i am questioning if this solution is “clean”:

pos points to the current element of the input array arr and as long as there are more elements in arr, the while loop keeps looping.
The sub-arrays of output-array arr2 get their slice of arr, starting at the current pos (which increments by the input size after each loop) and ending at the position pos + size.

Is this clean code - the last subarray may be shorter than the size input (the slice of arr is for example four elements long while there are only three elements “left” at the end of arr)?

Does this cause (internal) errors while the execution of the program and if so is this “okay”?, or is to be intended okay (with the slice method) in javascript?

function chunkArrayInGroups(arr, size) {
  let pos = 0;
  let subArr = 0;
  let arr2 = [];

  if (size == 0) {
    return arr;
  }

  while ( pos < arr.length) {
    arr2[subArr] = arr.slice([pos], [pos + size]);
    pos += size;
    subArr++;
  }

  return arr2;
  
}

console.log(chunkArrayInGroups(["a", "b", "c", "d"], 1));

Challenge Information:

Basic Algorithm Scripting - Chunky Monkey

slice takes numbers as arguments, not arrays, this works for JavaScript magic (called type coercion), but you should not use arrays there.

You could use clearer variable names, to make it more easy to understand

1 Like

thanks, i don´t know why i used brackets there :rofl:

1 Like

Would pointer be a good name for “pos” or is counter more accurate?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.