0

I solved an algorithm challenge from FreeCodeCamp with the function below, but am wondering if this is a "good" way to solve the problem, most specifically, because I am setting my counter to i+=0 and splicing indices from the head. Have I created an anti-pattern here? Is there anything that would be more logical, and can you explain why? Thank you in advance for help!

function chunk(arr, size) {
  var newArr = [];
  for (i=0; i<arr.length; i+=0) { 
      var sliced = arr.slice(i, size);
      newArr.push(sliced);
      arr.splice(0, size);
  }
  return newArr;
}
chunk([0, 1, 2, 3, 4, 5, 6, 7, 8], 4);
returns--> [ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8 ] ]
2
  • 1
    You can look into Array.slice(). Also if objective of this question is to seek improvements, you should try CodeReviews instead Commented Feb 26, 2016 at 16:23
  • 1
    I'm voting to close this question as off-topic because it is asking for a codereview. ask on codereview.stackexchange.com Commented Feb 26, 2016 at 16:29

3 Answers 3

1

Have I created an anti-pattern here? Is there anything that would be more logical, and can you explain why?

your code contains a few improvable parts

function chunk(arr, size) {
  //newWhatever, myWhatever, ... look for a better naming like `out` or `result` 
  //or in this case `chunks` would describe the content of the variable
  var newArr = [];

  //you initialize `i` without the var-keyword, therefore you populate/pollute the global namespace
  //and instead of calculating i+=0, you can leave this part empty:
  //for(var i=0; i<arr.length; ){
  for (i=0; i<arr.length; i+=0) { 
      var sliced = arr.slice(i, size);
      newArr.push(sliced);

      //splicing (with P) is often a thing that should be avoided, 
      //- it is destructive (it destroys the input-array)
      //- it is slow, cause the engine has to allocate new memory 
      //  and copy the remaining elements over to this memory,
      //  and garbage-collect the old memory
      arr.splice(0, size);
  }
  return newArr;
}

a better solution would be:

function chunk(arr, size) {
    for(var chunks=[], i=0; i<arr.length; i+=size)
        chunks.push(arr.slice(i, size));
    return chunks;
}

assuming that the inputs are right.

For completenes, you should add some validation of the inputs. That arr is in place, can be sliced, and has a length-property.
And that size is an integer > 0 otherwise the code may create strange results.

function chunk(arr, size) {
    //checks if arr is not empty and arr.slice is not empty 
    //and casts the length-property to int
    //if anything "fails" len = 0;
    var len = (arr && arr.slice && arr.length)|0;

    //check if size is > 1 and is an integer
    if(size !== Math.floor(size) || size < 1)
        throw new Error("invalid chunl-size: "+size);

    for(var chunks=[], i=0; i<len; i+=size)
        chunks.push(arr.slice(i, size));
    return chunks;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Recursion, perhaps?

function chunk(arr, size, out) {

  // if the output array hasn't been passed in
  // create it
  out = out || [];

  // if there are no elements in the input array
  // return the output array
  if (!arr.length) return out;

  // push the "head" of the input array to the
  // output array
  out.push(arr.slice(0, size));

  // call chunk again with the "tail" of the input array
  return chunk(arr.slice(size), size, out);
}

DEMO

Comments

0
function chunk(arr, size) {
    var subArrayCount = arr.length / size;
    var res = [];
    for (i = 0; i < subArrayCount; i++) {
        var from = size * i;
        var to = (size * (1 + i));
        console.log(to)
        var sliced = arr.slice(from, to);
        res.push(sliced);
    }
    return res;
}
chunk([0, 1, 2, 3, 4, 5, 6, 7, 8], 4);
returns--> [ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8 ] ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.