0

This seems pretty basic, but I can't find the best method to do this... I'm trying to set up a function that loops between a user selected start and end variables. This is what I ended up with but I'm sure there is a better way to do it (demo).

Note: the x & y variables are indexed to one, not zero.

getWidths1 = function(x, y) {
    var start = (x < y) ? x : y,
        end = (x < y) ? y : x,
        total = 0;
    for (; start < end; start++) {
        total += values[start - 1] || 0;
    }
    return total;
};

I tried this function, but the results are one result off when y > x:

getWidths2 = function(x, y) {
    var total = 0,
        diff = (x < y) ? 1 : -1;
    while (x !== y) {
        total += values[x - 1] || 0;
        x += diff;
    }
    return w;
};

So, is the first function the best, or does someone have a better method?

1
  • 2
    Seems fine to me, but you could use start = Math.min(x, y); and end = Math.max(x, y); to make script more readable Commented Jul 18, 2011 at 23:27

3 Answers 3

3

The first isn't bad. I think this is slightly more traditional:

for (var i = start; i < end; i++){

}

Only real difference is that it doesn't affect start and end.

Sign up to request clarification or add additional context in comments.

Comments

1

I'd make a few changes:

Use Math.min and Math.max - much more readable.

Don't subtract one from start if the first value you want is values[start].

var getWidths1 = function(x, y) {
    var start = Math.min(x,y), end = Math.max(x,y);
    var total = 0;
    for (; start < end; start++) {
        total += values[start] || 0;
    }
    return(total);
}

Comments

0

I agree with @kingjiv with the added caveat that if you want to include the item at y then you need:

for (var i = start; i <= end; i++){
...
}

As it is your code (both versions) will total the values from x inclusive to y exclusive.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.