I'm wondering how it works. I guess that "right[r++]" increments "r" in while loop. Or it shows which element of "right" we push to "result"?
function merge(left, right){
var result = [],
lLen = left.length,
rLen = right.length,
l = 0,
r = 0;
while(l < lLen && r < rLen){
if(left[l] < right[r]){
result.push(left[l++]);
}
else{
result.push(right[r++]);
}
}
return result.concat(left.slice(l)).concat(right.slice(r));
}
Thank you.
I'm wondering how it works. I guess that "right[r++]" increments "r" in while loop. Or it shows which element of "right" we push to "result"?
function merge(left, right){
var result = [],
lLen = left.length,
rLen = right.length,
l = 0,
r = 0;
while(l < lLen && r < rLen){
if(left[l] < right[r]){
result.push(left[l++]);
}
else{
result.push(right[r++]);
}
}
return result.concat(left.slice(l)).concat(right.slice(r));
}
Thank you.
Share Improve this question asked Jan 14, 2016 at 18:55 Tima TruTima Tru 1861 gold badge4 silver badges17 bronze badges 1- the question is, what does not work, what is your problem? – webdeb Commented Jan 14, 2016 at 19:02
2 Answers
Reset to default 6result.push(right[r++]);
is essentially shorthand for
result.push(right[r]);
r = r + 1;
The ++ operator after the variable returns the variable's value before it gets incremented.
For parison, using it before the variable
result.push(right[++r]);
would achieve the same result as
r = r + 1;
result.push(right[r]);
right[r++] is same like writing this:
right[r]
r=r+1
This was called post-increment. There is also pre-increment. It would be written like this:
right[++r]
It would be eqvivalent to
r=r+1
right[r]