// // encoded in Unicode( UTF-8 ) // if you cannot see comments correctly, please // configure your web browser etc's option. // //---------------------------------- // C++のstd::vectorらしきもの。 //---------------------------------- function Vector() { // イテレータ function iterator(ar, p) { this.get = function() { return ar[p]; } this.set = function(rhs) { ar[p] = rhs; } this.nxt = function() { return new iterator(ar,p+1); } this.eq = function(rhs) { return rhs.eq_impl(ar,p); } this.eq_impl = function(x_ar,x_p) { return x_ar==ar && x_p==p; } } var ar = new Array(); this.begin = function() { return new iterator(ar,0); } this.end = function() { return new iterator(ar,ar.length); } this.push_back = function(x) { ar.push(x); } } //---------------------------------- // C++のstd::find_ifらしきもの。 // 関数、もしくは「callというメソッドをもったオブジェクト」 // を第三引数として渡すことが出来る。 // 同様に他の も全部簡単に書けます。 //---------------------------------- function find_if( s, e, f ) { for( ; !s.eq(e); s=s.nxt() ) if( f.call(null, s.get()) ) return s; return e; } //---------------------------------- // てきとーなVector v = new Vector(); v.push_back(1); v.push_back(3); v.push_back(5); v.push_back(7); //---------------------------------- // 普通の関数を渡す例 //---------------------------------- i = find_if( v.begin(), v.end(), function(x){return x>4} ); print( i.get() ); //---------------------------------- // callメソッド付きオブジェクトを渡す例 //---------------------------------- function bigger_than(x) { return { call: function(_,y){return y>x} }; } i = find_if( v.begin(), v.end(), bigger_than(5) ); print( i.get() ); //---------------------------------- // 数値に後付けでcallメソッドをつけちゃう例 //---------------------------------- Number.prototype.call = function(_,x) { return this == x; // 自分と等しければtrueを返す } i = find_if( v.begin(), v.end(), 3 ); print( i.get() ); delete Number.prototype.call; // callメソッド削除 (^^;