by jbanon · 14y ago · 0 comments
var i;
for (i = 0; i < 10; i++) {
doSomething();
}
for (i = 0; i < 10; i += 1) {
doSomething();
}
http://jashkenas.github.com/coffee-script/#try:for%20i%20in%... for i in [0...test]
doSomething()
for i in [0...test] by 1
doSomething()
compiles to: var i;
for (i = 0; 0 <= test ? i < test : i > test; 0 <= test ? i++ : i--) {
doSomething();
}
for (i = 0; i < test; i += 1) {
doSomething();
}
the latter one being much faster because it isn't testing the direction the counter should be going all the time.Not knowing CoffeeScript well, when I see this code:
n = -10 for i in [0...n] doSomething()
I'd expect it to call doSomething zero times. At least that's what I'd expect in JavaScript or any of the other languages I've used.
for i in [10..0]
I've opened a ticket to discuss this further: https://github.com/jashkenas/coffee-script/issues/1952 for i in [a...b]
becomes if(a <= b) {
for(i = a; i < b; i++) {
// Code
}
} else {
for(i = a; i > b; i--) {
// Code again
}
}
Or otherwise moved the extra conditions outside the loop so they only get computed once?