Please review the code below, note the condition of my for loop depends on the step parameter.
Rather than every time the condition is executed it determines which branch to use, I would like to test that once - I had supposed I could create a delegate or of the condition but it doesn't seem to work.
Is it possible in JS to do this?
Code:
function(start, end, step) {
if (step === undefined) {
step = 1;
}
var result = [];
for (; (step < 0) ? start >= end : start <= end; start += step) {
result.push(start);
}
return result;
}
My attempt:
function(start, end, step) {
if (step === undefined) {
step = 1;
}
var condition = (step < 0) ? start >= end : start <= end;
var result = [];
for (; condition; start += step) {
result.push(start);
}
return result;
}
asked Mar 11, 2016 at 0:52
shenku
12.5k14 gold badges67 silver badges126 bronze badges
1 Answer 1
To do this, you need to make condition a function, like below. But even if you do, the condition is still executed at every iteration of the loop.
var condition = (step < 0) ?
function(start){
return start >= end;
} :
function(start){
return start <= end;
};
var result = [];
for (; condition(start); start += step) {
result.push(start);
}
answered Mar 11, 2016 at 1:08
GreenGiant
5,3242 gold badges56 silver badges86 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
startis ever changed. A hack way would be to define each as a function instead. There's definitely a better way though. I'll walk on it.