DEV Community

Discussion on: [javascript] Array Partitioning by Length

Collapse
 
avalander profile image
Avalander

Are you aware that your function is both returning a new instance of an array and mutating the array provided as an input? That's bound to be confusing to anyone using that function, maybe it should just do one or the other.

Collapse
 
slimdestro profile image
D\sTro

yeah you're right. its returning new array to keep things clear. like on demand you can say which means its total new instead tempering oute properties. this one you asked right :

array.forEach(function(x, y) {
// partition
}, array);

// this would not yield new instance but i didnt infroce use of map/reduce/filter etc. its like a plain pure javascript touch

Collapse
 
avalander profile image
Avalander

I don't really understand how forEach is supposed to help here, the thing is that you are using Array.prototype.splice, which mutates the original array.

If you run this code:

const a = [ 1, 2, 3, 4 ]
groupInString(a, 2)
console.log(a)
Enter fullscreen mode Exit fullscreen mode

You'll see that your function, besides returning the array [ '12', '34' ] mutated a into [ null, null ] as a side effect, which is inconvenient if somebody intended to use that array in several operations.

It is a lot better if functions return new values without modifying the input values. Without making big changes, you can fix your function not to modify the input array by using slice instead of splice.

const groupInString = (array, length) => {   
    const newArr = []
    for(let i = 0; i < array.length; i+= length) {
        newArr.push(
            array.slice(i, i + length).join('')              
        )
    }
    return newArr
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
slimdestro profile image
D\sTro

i got your point now. i have added both thru splice() as well as slice(). thanks for pointing out this friction. appreciate it