ES6 の generator を traceur で使う

traceur とは、Googleの開発するES6 to ES5コンパイラである。npm経由で簡単にインストールでき、typemapにも対応している。ES6の対応状況はわからないが、generatorは使えるようだ。

以下公式ドキュメントからの抜粋*1

// A binary tree class.
function Tree(left, label, right) {
  this.left = left;
  this.label = label;
  this.right = right;
}
// A recursive generator that iterates the Tree labels in-order.
function* inorder(t) {
  if (t) {
    yield* inorder(t.left);
    yield t.label;
    yield* inorder(t.right);
  }
}

// Make a tree
function make(array) {
  // Leaf node:
  if (array.length == 1) return new Tree(null, array[0], null);
  return new Tree(make(array[0]), array[1], make(array[2]));
}
var tree = make([[['a'], 'b', ['c']], 'd', [['e'], 'f', ['g']]]);

// Iterate over it
for (var node of inorder(tree)) {
  console.log(node); // a, b, c, d, ...
}

実行方法:

$ traceur a.js # コンパイルして実行する
a
b
c
d
e
f
g
$ traceur --out compiled.js a.js # コンパイルしてファイルに保存する

*1:letは使えなかった