musictheory / NilScript

Objective-C-style language superset of JavaScript with a tiny, simple runtime
Other
50 stars 5 forks source link

@each support #36

Closed iccir closed 9 years ago

iccir commented 9 years ago

In general, I'm not a fan of "let's make oj a complex language!"

That said, I think there is benefit to adding a very basic iterator for array-like objects.

Right now, the following is the fastest way to loop in most js engines:

for (var i = 0, length = arr.length; i < length; i++) {
    var object = arr[i];
    // ...
}

Using _.each or Array#forEach looks nicer, but it performs slower:

_.each(arr, function(object) {
    // ...
});

There is also no nice way to break, and return is used for continue. This has led to programming errors when refactoring (See #35)

Hence, I'm proposing:

@each (object in arr) {
    // ...
}
iccir commented 9 years ago

The scope of the object variable would be limited to the @each block.

Also, this would only be for arrays. It would transpile into something like:

for (var $oj_each_UUID_i = 0, $oj_each_UUID_length = arr.length; $oj_each_UUID_i < $oj_each_UUID_length; $oj_each_UUID_i++) {
    var $oj_each_UUID_object = arr[i];
    // All occurrences of object identifier replaced by $oj_each_UUID_object
}
iccir commented 9 years ago

Actually, we should use the same semantics as for-in loops.

var object;
@each (object in arr) { }

@each (var object in arr) { }

@each (let object in arr) { }