Created
May 22, 2012 09:05
-
-
Save ishiduca/2767737 to your computer and use it in GitHub Desktop.
ライン文字列をパースし、その結果ごとに何かをさせる
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Command () { this.map = []; } | |
(function (cp) { | |
cp.set = function (pattern, cb) { | |
if (typeof cb !== 'function') | |
throw new Error('2nd argument must be "function"'); | |
if (typeof pattern !== 'string' && ! pattern instanceof RegExp) | |
throw new Error('1st argument must be "string" of "regexp"'); | |
this.map.push([ pattern, cb ]); | |
return this; | |
}; | |
cp.parse = function (input) { | |
var i = 0 | |
, len = this.map.length | |
, item | |
; | |
for (var i = 0, len = this.map.length; i < len; i++) { | |
item = this.map[i]; | |
if (typeof item[0] === 'string' && item[0] === input) | |
return [ item[1], [ input ] ]; | |
if (item[0] instanceof RegExp && item[0].test(input)) | |
return [ item[1], input.match(item[0]) ]; | |
} | |
}; | |
})(Command.prototype); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var cmd = new Command; | |
cmd.set(':list', function (args) { | |
storage.list(); | |
}) | |
.set(/^:(mak|nam|gnr|com|mch|act)\s+(.+?)$/, function (args) { | |
storage.find({ category : args[1] | |
, value : args[2] | |
}); | |
}) | |
.set(/^[^:].*?$/, function (args) { | |
storage.find({ category : 'mak' | |
, value : args[0] | |
}); | |
}) | |
; | |
$('#form1').onsubmit(function () { | |
var res = cmd.parse($("#query").value); | |
if (! res) return $('statusline').innerHTML = | |
escapeHTML('#quey.value is not "command"'); | |
res[0](res[1]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment