User:Jarble/Natural language user interface
Appearance
This is an English-to-JavaScript translator. Here's an online demo of this script.
//getOutput is the function that converts English statements into JavaScript statements
alert(getOutput("3 is greater than 4")); //prints false
alert(getOutput("4 is greater than 3")); //prints true
alert(getOutput("2 to the power of 3")); //prints 8
getOutput("print hello 5 times"); //prints hello 5 times
function isAString(theString){
return (typeof theString === 'string' || theString instanceof String);
}
function trimString(theString){
//alert(JSON.stringify(theString) + " is theString");
//alert(theString.substring(1, theString.length));
return theString.substring(1, theString.length);
}
function getOutput(inputString){
var theList = inputString.split(" ");
function startsAndEndsWith(theString){
if(isAString(theString)){
return theString.charAt(0) === "@";
}
return false;
}
var p = {};
function matchesPattern(pattern){
var thePattern = pattern.split(" ");
for(var i = 0; i < theList.length; i++){
if(!startsAndEndsWith(thePattern[i])){
if(theList[i] !== thePattern[i]){
return false;
}
}
else{
//alert("Adding "+thePattern[i])
p[trimString(thePattern[i])] = theList[i];
}
}
//alert(thePattern);
//alert(theList);
return true;
}
dictionary = {
"@foo is greater than @bar": function(){
return (p.foo > p.bar);
},
"@foo is less than @bar": function(){
return (p.foo < p.bar);
},
"@foo to the power of @bar": function(){
return Math.pow(p.foo, p.bar);
},
"@a is divisible by @b": function(){
return (p.a % p.b === 0);
},
"print @a @b times":function(){
for(var i = 0; i < p.b; i++){
alert(p.a);
}
}
};
for (var key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
if(matchesPattern(key)){
return dictionary[key]();
}
}
}
}