JSFiddle - React, Tailwind, and code Playground

by ilazarte

HTML

<ul>
    <li class="state_food_hot">soup</li>
    <li class="state_cold_food">sandwhich</li>
    <li class="state_food_hot_spicy">curry</li>    
</ul>

JavaScript

var nodal = {};
nodal.util = {};
nodal.css = {};
nodal.css.state = {};

/*
 * safely split a string into an array
 * always returns an array instance regardless of string
 * if no delimiters are found, returns an array of single value containing string
 */
nodal.util.split = function(str, ch) {
    if (str == null || str == "") {
        return null;
    }
    if (str.indexOf(ch) == -1) {
        return [str];
    }
    return str.split(ch);
}

nodal.util.startsWith = function(str, substr) {
    if (str == null || str == "") {
        return false;
    }
    return str.indexOf(substr) == 0;
}

nodal.util.contains = function(arr, val) {
    var contains = false;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == val) {
            contains = true;
            break;
        }
    }
    return contains;
}

/**
 * add the states to the class name
 */
nodal.css.state.add = function(clsStr, newstates) {
    var sarr = [];
    
    if (!nodal.util.startsWith(clsStr, "state")) {
        return clsStr;
    }

    var states = clsStr.substr(6);
    sarr = nodal.util.split(states, "_");
    
    for (var i = 0; i < newstates.length; i++) {
        var state = newstates[i];
        if (!nodal.util.contains(sarr, state)) {
            sarr.push(state);
        }
    }

    sarr.sort();
        
    var newClsName = "state_" + sarr.join("_");
    return newClsName;
}
    
/**
 * remove the states from the class name
 */
nodal.css.state.remove = function(clsStr, oldstates) {

    if (clsStr.indexOf("state") == -1) {
        return clsStr;
    }

    var states = clsStr.substr(6);
    var sarr = nodal.util.split(states, "_");
    var newsarr = [];
    
    for (var i = 0; i < sarr.length; i++) {
        if (!nodal.util.contains(oldstates, sarr[i])) {
            newsarr.push(sarr[i]);
        }
    }

    newsarr.sort();
    
    var newClsName = "state_" + newsarr.join("_");
    return newClsName;
}

/**
 * for each class in the node class attribute, push the...