Help with algorithm using compromise library

Hello,
I’m writing something to change verbs in text. I’m using the compromise library. What I want to do is prevent the verb in the foreach loop from changing if it is in the ignoreVerbs array.

var verbs = doc.verbs().out('array');
var ignoreVerb = ['was', 'is', 'do', 'did', 'does'];
verbs.forEach(function(verb) {
        if (Math.random() < 0.3) {
            var re = new RegExp('\\b'.concat(verb, '\\b'));
            var chosen_style = verb_style[Math.floor(Math.random()*3)];
            modified_text = modified_text.replace(re, chosen_style.concat('$&</span>'));
        }
    });

You could just update the condition, so that it checks if the verb isn’t in the ignoreVerb array.

if (ignoreVerb.indexOf(verb) === -1 && Math.random() < 0.3) {

That way it won’t even happen if that verb is in the array.

A better way though is to first filter that list of verbs to remove ones that are in the ignoreVerb array.

Why is that better? It’s better because the code to choose a random verb doesn’t ever need to know anything more than what it’s supposed to do.

verbs.filter(function (verb) {
    return ignoreVerb.indexOf(verb) === -1;
}).forEach(function (verb) {
    if (Math.random() < 0.3) {
        // ...
    }
});

Thanks @Paul_Wilkins! I’ll try this!
Do you believe the .some could be another option here?

No, .some() only gives you a boolean value, to tell you if at least one of the array items matched the criteria.
It’s a more complex way of doing Array.indexOf()

Thanks for pointing me in the right direction @Paul_Wilkins! It works great.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.