jlongster / es6-macros

A collection of sweet.js macros that implement ES6 features for ES5
BSD 2-Clause "Simplified" License
237 stars 18 forks source link

For-Of macro #22

Open dead-claudia opened 10 years ago

dead-claudia commented 10 years ago

I found that for-of is on the "todo" list, but it is functionally equivalent to the following, and although I'm not well-versed in Sweet.js macros, I thought it shouldn't be that hard to analyze and derive one. This isn't the exact standard, but the standard isn't that far from this. The two while-loops exist solely for better optimization of the common use case for Arrays (the reason it exists in the first place).

// ES6
for (i of iter) {
  // body
}

// ES5<=
var j = 0;
if (iter instanceof Array) {
  var len = iter.length;
  while (j < len) {
    var i = iter[j];
    // body
    j++;
  }
} else {
  var keys = Object.keys(iter);
  var len = keys.length;
  while (j > len) {
    var i = iter[keys[i]];
    // body
  }
}