Forum Moderators: open

Message Too Old, No Replies

Faster / shorter than multiple indexOf

         

csdude55

5:02 am on Aug 24, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have about 125 lines that are essentially the same thing over and over:

if (
foo.indexOf('123') !== -1 ||
foo.indexOf('456') !== -1
) {
// do this
}

if (
foo.indexOf('789') !== -1 ||
foo.indexOf('101') !== -1 ||
foo.indexOf('112') !== -1 ||
foo.indexOf('131') !== -1
) {
// do something else
}


Is there a better way to test the same variable over and over to see if it contains specific strings like that, rather than several indexOf?

I know that I could use if (/123|456/.test(foo)) { ... }, but would a regex actually process faster? Or would it just be a smaller initial download traded off for slower processing on every function call?

Fotiman

3:01 pm on Aug 24, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Is foo an array or a string?

Fotiman

3:31 pm on Aug 24, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Unless you're performing thousands of these conditional checks, the difference in processing speed is going to be immeasurable.

I would suggest approaching this from a more declarative syntax. I'd use `includes` instead of `indexOf`, and I'd use the array `some` method instead of multiple OR conditions, and I'd put your input in an array:


if (['123', '456'].some(item => foo.includes(item))) {
// do this
}


If you'll use that check to see if the item is in foo multiple times, then perhaps put it in a variable:


const isInFoo = item => foo.includes(item);
if (['123', '456'].some(isInFoo)) {
// do this
}

if (['789', '101', '112', '131'].some(isInFoo)) {
// do something else
}


And then I might consider putting each of these in their own function instead. Not knowing the context of what these values represent, I can't suggest good function names, but it would be something like this:


const isInFoo = item => foo.includes(item);
const isFruit = () => ['123', '456'].some(isInFoo);
const isVeggy = () => ['789', '101', '112', '131'].some(isInFoo);

if (isFruit()) {
// do this
}

if (isVeggy()) {
// do something else
}


The code becomes much more readable, and easy to maintain.