7

Noob question. I am trying to write a for loop with a range. For example, this is what I want to produce in JavaScript:

var i, a, j, b, len = arr.length;
for (i = 0; i < len - 1; i++) {
    a = arr[i];
    for (j = i + 1; i < len; j++) {
        b = arr[j];
        doSomething(a, b);
    }
}

The closest I've come so far is the following, but

  1. It generates unnecessary and expensive slice calls
  2. accesses the array length inside the inner loop

CoffeeScript:

for a, i in a[0...a.length-1]
    for b, j in a[i+1...a.length]
        doSomething a, b

Generated code:

var a, b, i, j, _i, _j, _len, _len1, _ref, _ref1;

_ref = a.slice(0, a.length - 1);
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  a = _ref[i];
  _ref1 = a.slice(i + 1, a.length);
  for (j = _j = 0, _len1 = _ref1.length; _j < _len1; j = ++_j) {
    b = _ref1[j];
    doSomething(a, b);
  }
}

(How) can this be expressed in CoffeeScript?

2 Answers 2

10

Basically, transcribing your first JS code to CS:

len = arr.length
for i in [0...len - 1] by 1
  a = arr[i]
  for j in [i + 1...len] by 1
    b = arr[j]
    doSomething a, b
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that works. I don't understand why it still generates a few unnecessary loop counters, but I can live with that.
@alekop I think the main rational for those extra counters is that if you happen to modify the loop variable (i or j) inside the loop, you don't change the loop's iterations.
1

Seems like the only way to avoid the extra variables is with a while loop http://js2.coffee

i = 0
len = arr.length 

while i < len - 1
  a = arr[i]
  j = i + 1
  while j < len
    b = arr[j]
    doSomething a, b
    j++
  i++

or a bit less readable:

i = 0; len = arr.length - 1
while i < len
  a = arr[i++]; j = i
  while j <= len
    doSomething a, arr[j++]

2 Comments

That's not exactly what the original code does. The outer loop range is 0..n-1, while the inner range is i+1..n.
@alekop sorry about that .. I didn't read the question carefully.

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.