jlongster / es6-macros

A collection of sweet.js macros that implement ES6 features for ES5

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

For-Of macro

dead-claudia opened this issue · comments

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
  }
}