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>
    <li>Turn the light in the kitchen on and the fan in the bedroom off</li>
    </ol></em>
    <strong>NOTE:</strong> This will not work for sentences like:<em><ol>
    <li>Turn my kitchen fan and my bedroom lights on and living room lights off.</li>
    <li>Turn on the bedroom light</li>
    </ol>
        
    </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', 'light', 'fan' ];

// Functions to test what a word is
function isState(word) { return is(word, states); }
function isPlace(word) { return is(word, places); }
function isThing(word) { return is(word, things); }
              
// Function to do a single action
function doAction(state, place, thing) { 
    var str = 'Turn '+thing+' in '+place+' '+state;
    $('#answer').append(str+'<br>');    
}

// Function to do multiple actions 
function doActions(state, places, things) {
    for (j = 0; j < places.length; j ++) {
        for (k = 0; k < things.length; k++) {
            doAction(state, places[j], things[k]);
        }
    }
}

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 currentPlaces = Array();
    var currentThings = Array();
    
    for (i = inArray.length-1; i >= 0; i --) {
        var word = inArray[i];
    
        if (isState(word)) { 
            console.log("Found state: ", word);
            
            
            // Do any outstanding actions (on the old state) ...
            if (currentState) { 
                doActions(currentState, currentPlaces, currentThings);
            }
            // Store the new state
            currentState = word;
            // A state is always the end of a clause
            // so forgot all the places and things
            currentPlaces = Array();
            currentThings =...