Here is a light command line I built with JavaScript. I would like to ask if there are many stupidities, bad code and such? The only test command right now is add arg1 arg2
so writing add 1 1
should get you >>> 2
. It will print Command *** not found
with other commands than add
. See the fiddle below.
jsfiddle.net http://jsfiddle.net/Nr2Am/26/
JavaScript
function cli_focus() {
var cli = document.getElementById("commandline");
cli.focus();
}
function arguments_to_array(args) {
var arr = new Array();
for (var i=0; i<args.lentgh; ++i) {
arr[i] = args[i];
}
return arr;
}
function cli_go(input) {
var lines = input.value;
var lines_arr = lines.split(/\n+/);
var cmd = lines_arr[lines_arr.length-1];
cli_run(cmd);
return false;
}
function cli_parse(cmd) {
return cmd.split(/\s+/);
}
function cli_remove_blank_words(words) {
while (words.length>0 && words[0]==="") {
words = words.slice(1);
}
while (words.length>0 && words[words.length-1]==="") {
words = words.slice(0, words.length-1);
}
return words;
}
function cli_run(cmd) {
var words = cli_parse(cmd);
words = cli_remove_blank_words(words);
var last_word = null;
for (var i=0; i<words.length; ++i) {
var func_name = words.slice(0, i+1).join("_");
if (window[func_name] === undefined) {
break;
} else {
last_word = i;
}
}
if (last_word===null || words.length===0) {
document.getElementById('commandline').value = document.getElementById('commandline').value + '\n>>> Command ' + words[0] + ' not found';
return;
}
var func_name = words.slice(0, last_word+1).join( "_" );
var func = window[func_name];
var args = words.slice(last_word+1);
func.apply(this, args);
}
function add(a,b) {
var result = parseInt(a)+parseInt(b);
document.getElementById('commandline').value = document.getElementById('commandline').value + '\n>>> ' + result;
}