昨日は13日の金曜日だったので、JavaScriptでJSONと戯れました
ということで、JSONにチェーンソーメソッドチェーンを与えてみる。
Object.prototypeを汚しちゃうなんてお行儀悪いけど、仕方ないじゃない、ジェイソンなんだもん。お行儀悪い男の子なんだもん。
Object.prototype.show = function() { if (this.head) { console.log(this.head); } else { return '死んだ'; } if (this.body) console.log(this.body); if (this.foot) console.log(this.foot); } Object.prototype.chop = function() { if (!this._body) { this._body = this.body; this._foot = this.foot; } var clone = this; var chop_body = function() { var reg = /(\s*?)(\S)(\s*?)(\S)(\s*?)(\S)/; var default_body = reg.exec(clone._body); var space = (encodeURIComponent(default_body[2]).length === 3) ? ' ' : ' '; if (clone.body.match(reg)) { var num = Math.floor(Math.random()*2); clone.body = (num === 0) ? default_body[1] + space + default_body.slice(3).join('') : default_body.slice(1,5).join(''); } else if (clone.body.match(/\s*?\S\s*?\S/)) { (function() { var reg = /(\s*?)(\S)(\s*?)(\S)/; var current_body = reg.exec(clone.body); var space = (encodeURIComponent(current_body[2]).length === 3) ? ' ' : ' '; if (current_body[4] === default_body[4]) { clone.body = current_body[1] + space + current_body.slice(3).join(''); } else if (current_body[2] === default_body[4]) { clone.body = current_body.slice(1,3).join(''); } })(); } else if (clone.foot) { chop_foot(); } else { delete clone._foot; delete clone.body; } }; var chop_foot = function() { var reg = /(\s*?)(\S)(\s*?)(\S)/; var default_foot = reg.exec(clone._foot); var space = (encodeURIComponent(default_foot[2]).length === 3) ? ' ' : ' '; if (clone.foot.match(/\s*?\S\s*?\S/)) { var num = Math.floor(Math.random()*2); clone.foot = (num === 0) ? default_foot[1] + space + default_foot.slice(3).join('') : default_foot.slice(1,3).join(''); } else { delete clone._foot; delete clone.foot; } }; var num = Math.floor(Math.random()*2); if (num === 0) { if (clone.body) { chop_body(); } else if (clone.foot) { chop_foot(); } else { delete clone.head; } } else if (num === 1) { if (clone.foot) { chop_foot(); } else if (clone.body) { chop_body(); } else { delete clone.head; } } return clone; }; var JSON1 = { head : ' ●', body : ' /■\', foot : ' ||' }; var JSON2 = { head : ' □', body : ' 「 |>', foot : ' 「\', }; // 使い方 /* JSON1.chop().chop().chop().show(); JSON2.chop().chop().show(); JSONは、メソッドチェーンを装備しています。 JSONに、頭と体と足を与えます。右手と左手、右足と左足は別々に与えます。 chopの数だけ切られます。showでどこまで切られたか見れます。 たくさん切ると死にます。結構しぶといです。 */
楽しいなー。JavaScript楽しいなー。