Skip to content

Instantly share code, notes, and snippets.

@nakamura-to
Created August 8, 2013 12:51
Show Gist options
  • Save nakamura-to/6184298 to your computer and use it in GitHub Desktop.
Save nakamura-to/6184298 to your computer and use it in GitHub Desktop.
Rubyのブロック付きメソッド相当をECMA Script 6で。「初めてのRuby」の「7.3.3 ブロック付きメソッドの定義」を参考に。node v0.11.4で--harmony-generatorsオプションをつけて実行。
/*
* ブロック付きメソッドのファクトリ
*/
function ruby(fn) {
return run;
function run(block) {
var block_given = typeof block === 'function';
var each = function * (array) {
for (var i = 0, len = array.length ; i < len; i++) {
yield array[i];
}
};
var gen = fn.call({block_given: block_given, each: each});
var ret = gen.next();
var v;
while (!ret.done) {
if (block_given) {
v = block(ret.value);
}
ret = gen.next(v);
}
return ret.value;
}
}
/*
* Example 1
*/
var foo_bar_baz = ruby(function * () {
yield 'foo';
yield 'bar';
yield 'baz';
});
foo_bar_baz(function (item) {
console.log(item);
});
// foo
// bar
// baz
/*
* Example 2
*/
var foo_bar_baz2 = ruby(function * () {
yield * this.each('foo bar baz'.split(' '));
});
foo_bar_baz2(function (item) {
console.log(item);
});
// foo
// bar
// baz
/*
* Example 3
*/
var foo_bar_baz3 = ruby(function * () {
if (!this.block_given) return foo_bar_baz3;
yield * this.each('foo bar baz'.split(' '));
});
foo_bar_baz3(function (i) {
console.log(i);
});
// foo
// bar
// baz
foo_bar_baz3()(function (i) {
console.log(i);
});
// foo
// bar
// baz
/*
* Example 4
*/
var my_map = ruby(function * () {
return [yield 1, yield 2, yield 3];
});
console.log(my_map(function (i) { return i + 1;})); // [2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment