JSFiddle - React, Tailwind, and code Playground
by SpaceDog
HTML
Try strings like this: <BR>
<em><ol>
<li>Turn my kitchen lights on and my bedroom and living room lights off.</li>
<li>Turn my kitchen lights on and my bedroom lights on and living room lights off.</li>
<li>Turn my kitchen and my bedroom and living room lights off.</li>
</ol>
</em>
<input id='inString'></input>
<button id='go'>Parse It</button>
<div id='answer'></div>
JavaScript
// functions to make it easier to read the main logic
// Check if 'word' is in 'array'
function is(word, array) {
return (($.inArray(word, array)) != -1);
}
// Arrays of things
var states = [ 'on', 'off' ];
var places = [ 'kitchen', 'bedroom', 'living' ];
var things = [ 'lights', 'fan' ];
// Test functions
function isState(word) { return is(word, states); }
function isPlace(word) { return is(word, places); }
function isThing(word) { return is(word, things); }
function doAction(state, place, thing) {
var str = 'Turn '+thing+' in '+place+' '+state;
$('#answer').append(str+'<br>');
}
function parseIt() {
// Get the input
var inString = $('#inString').val();
// Preprocess string (probably need to do much more here)
inString = inString.toLowerCase().replace(/[.,]/,'')
// Make it an array
var inArray = inString.split(" ");
// Clear the answer area
$('#answer').html("");
// Process the string
var currentState = null;
var currentPlace = null;
var currentThing = null;
for (i = inArray.length-1; i >= 0; i --) {
var word = inArray[i];
if (isState(word)) {
console.log("Found state: ", word);
currentState = word;
currentPlace = null;
currentThing = null;
} else if (currentState) {
if (isThing(word)) {
console.log("Have state, found thing: ", word);
currentThing = word;
currentPlace = null;
} else if (currentThing) {
if (isPlace(word)) {
console.log("Have state, thing, found place: ", word);
currentPlace = word
doAction(currentState, currentPlace, currentThing);
}
// skip non-place, thing or state word.
}
// Skip when we don't have a thing to go with our state
}
...