简体   繁体   中英

switch for all cases

I want to check if any strings that was entered belongs to the class Noun.

var answer = prompt("enter sentence").toLowerCase();

function Noun(name) {
    this.name = name;
}

spoon = new object("noun");

Can i find match between any substring like wwwspoonwww and belonging to any class?

 var analysis = function(string) {
    switch (true) {
        case /any string/.test(string):
        if (?){
            console.log("noun");
        }
        else {
            console.log("not noun")
        };
        break;
    }
 };
 analysis(answer);

To check if a certain string is within another string you can use str.indexOf(string);

You do not need to use the switch in this case. But "for all cases" you would use default:

You want to find if there was a noun class instanciated with that string? - @plalx

Yes i do - @pi1yau1u

In that case you could use a map to store all newly created instances and implement an API that allows you to retrieve them by name or retrieve the whole list. I also implemented a findIn instance method that will return you the index of that noun in a specified string, or -1 if not found.

DEMO

var Noun = (function (map) {

    function Noun(name) {
        name = name.toLowerCase();

        var instance = map[name];

        //if there's already a Noun instanciated with that name, we return it
        if (instance) return instance;

        this.name = name;

        //store the newly created noun instance
        map[name] = this;
    }

    Noun.prototype.findIn = function (s) {
        return s.indexOf(this.name);
    };

    Noun.getByName = function (name) {
        return map[name.toLowerCase()];
    };

    Noun.list = function () {
        var m = map, //faster access
            list = [], 
            k;

        for (k in m) list.push(m[k]);

        return list;
    };

    return Noun;

})({});

new Noun('table');
new Noun('apple');

//retrieve a noun by name
console.log('retrieved by name :', Noun.getByName('table'));

//check if a string contains some noun (without word boundaries)
var s = 'I eat an apple on the couch.';

Noun.list().forEach(function (noun) {
    if (noun.findIn(s) !== -1) console.log('found in string: ', noun);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM