JavaScriptで配列の結合を"+"で書きたい.

やりたいことはタイトルのとおり.

要はオーバーロードしたいお...

※※※※ こういう願いは既出であること間違いないっ,

※※※※ よってここに書いてること, あるいは

※※※※ さらにエレガントな事がどっかに書かれてるかもしれないっ!!!

とりあえずECMA-262を読んでみる.

[p.74] 11.6.1 The Addition operator(+)

読むのがめんどくさいが, 要はReturn the String that hogehogeか,

ToNumber(左辺)とToNumber(右辺)の和を返すことしかできない.

オーバーロードとかできねーーーー

(配列を返せない)

んじゃ, 汚いけど, String介してやればいいか...???

> Array.prototype.toString = function(){return this.join(',') + ','}
[Function]
> String.prototype.toArray = function(){return this.split(',').slice(0,-1)}
[Function]
> ([1, 2, 3] + [4, 5, 6]).toArray()
[ '1', '2', '3', '4', '5', '6' ]

型がエ...

コンストラクタ読んで, evalしてやるか...

> Array.prototype.toString = function(){return this.map(function(x){return x.constructor.name + '(' + x + '),'}).join('')}
[Function]
> String.prototype.toArray = function(){return this.split(',').slice(0, -1).map(function(x){return eval(x)})}
[Function]
> ([1, 2, 3] + [4, 5, 6]).toArray()
[ 1, 2, 3, 4, 5, 6 ]

おおお...

続き

> ([1, 2, 3] + [4, 5, 6] + ['foo', 'bar']).toArray()
ReferenceError: foo is not defined

あちゃー, 結合するときにString(foo)ってなって, こりゃアカンがな...

んじゃあ…文字列は特別処理

> Array.prototype.toString = function(){return this.map(function(x){return x.constructor.name + '(' + (typeof x=='string' ?"'" + x + "'":x) + '),'}).join('')}
[Function]
> String.prototype.toArray = function(){return this.split(',').slice(0, -1).map(function(x){return eval(x)})}
[Function]
> ([1, 2, 3] + [4, 5, 6] + ['foo', 'bar']).toArray()
[ 1, 2, 3, 4, 5, 6, 'foo', 'bar' ]

おおおおお!?!??!??!?

> ([1, 2, 3] + [4, 5, 6] + ['foo', 'bar'] + [{"a": "b"}]).toArray()
SyntaxError: Unexpected identifier

こりゃだめだわ...

eval("Object([object Object])")はできない....

うーむ...どうするか...

困ったときのJSON

> Array.prototype.toString = function(){return this.map(function(x){return JSON.stringify(x) + ','}).join('')}
[Function]
> String.prototype.toArray = function(){return JSON.parse('[' + this.slice(0, -1) + ']')}
[Function]
> ([1, 2, 3] + [4, 5, 6] + ['foo', 'bar'] + [{"a": "b", c: [ 1, "foo"]}]).toArray()
[ 1, 2, 3, 4, 5, 6, 'foo', 'bar', { a: 'b', c: [ 1, 'foo' ] } ]

キタ?

キタカモ???

> ([] + []).toArray()
[]
> ([] + [1] + [[[], {x: []}]]).toArray()
[ 1, [ [], { x: [] } ] ]
> ([] + [null] + [true, false]).toArray()
[ null, true, false ]
> a = [1, 2, 3], x = 5, b = "baz"
'baz'
> (a + [x] + [b]).toArray()
[ 1, 2, 3, 5, 'baz' ]

...できたかもしれぬ...

欠点はいちいちカッコで括って関数書かなきゃいけないとこだけど...

よっしゃああああああああーーーーーーー!!!!!

> f = function (x) { return x; }
[Function]
> ([1, 2, 3] + [4, f]).toArray()
SyntaxError: Unexpected token ILLEGAL

\(^o^)/

結論: JavaScript演算子をいじろうとしちゃいかん.