While working on dynamically slicing an array, I noticed that my while
loop was causing an extra slice to be added when it broke the conditional. Even though I can achieve the desired functionality by removing the last element with arr.pop()
, I am curious as to why this is happening.
slices(num){
let arr = [this.digits.slice(0, num)]
let i = 0
if (this.digits.length < num){
throw new Error('Slice size is too big.')
} else {
while (arr[i].length === num){
i++
arr.push(this.digits.slice(i, num + i))
}
// arr.pop() - removed for testing
return arr
}
}
For example, let's say we want to slice the following array:
this.digits = [ 3, 1, 0, 0, 1 ]
The expected output should be:
[3, 1, 0], [1, 0, 0], [0, 0, 1]]
However, without using arr.pop()
, the algorithm unexpectedly adds an extra iteration resulting in a slice with less length than what is required by the conditional (num == 3
)
The actual output will look like:
[[3, 1, 0], [1, 0, 0], [0, 0, 1], [0, 1]]
I understand why the last element is being added due to the fulfillment of the conditional by the previous element. How can I elegantly handle this issue without resorting to using .pop()?
Thank you all for your solutions and feedback! While all responses seem effective, Peter B's implementation stood out for its simplicity and effectiveness. Just a few tweaks and it worked perfectly. Thank you once again!