Don't put console.log
calls in you functions unless there's a really good reason to. In this case, you're just printing the input, which is pretty pointless. It can also contribute greatly to the function's running time, since printing a large array isn't exactly free (a lot depends on how the runtime handles output)
You can simplify the code. You can do without slicing, reversing and applying chunks of the array
I'd just use two for-loops:
function selReverse(array, chunkSize) {
var output = [],
l = array.length;
for(var i = 0 ; i < l ; i += chunkSize) {
var start = Math.min(i + chunkSize, l) - 1;
for(var j = start ; j >= i ; j--) {
output.push(array[j]);
}
}
return output;
}
Edit: The code above doesn't work, but I thought it was due to very large inputs or something, but that's not the case.
The simple solution is basically, that the for
loop - both in my code and the original code - goes into an infinite loop if the chunkSize
is zero. This works, though:
function selReverse(array, chunkSize) {
var output = [],
l = array.length;
if(chunkSize === 0) return array.slice(); // could also do <= 0 to be safer
for(var i = 0 ; i < l ; i += chunkSize) {
var start = Math.min(i + chunkSize, l) - 1;
for(var j = start ; j >= i ; j--) {
output.push(array[j]);
}
}
return output;
}
Since it's got nothing to do with large inputs, I imagine the original code works just as well, as long as it too checks for the chunkSize
.
length
-length subsection; is that correct? If so, please edit your question to explain that. Thanks! \$\endgroup\$