0

There is a list of strings and I want to check if the one I check has a value from there.

For example, the list is "good", "amazing", "bad", "better", "worse"

and this function:

checkPositive = (str) => {
  if(str === "good" || str === "amazing" || str === "better") {
      return true;
    }
  return false;
}

My question is if it's possible to do it more efficiently than it is now, I don't like how that if statement looks.

4 Answers 4

2

You could use an array and .includes:

checkPositive = str => ['good', 'amazing', 'better'].includes(str)
Sign up to request clarification or add additional context in comments.

Comments

1

Build a dictionary:

let dict={
        good:  true
      , amazing: true
      , better: true
    };

checkPositive = str => { return dict[str]; } // dict[str] ? true : false, if you need actual boolean values 

Comments

0

You can use indexOf which will return -1 is the string is not present in list(assuming it is an array)

const strList = ["good", "amazing", "bad", "better", "worse"]

checkPositive = (str) => {
  return strList.indexOf(str) !== -1 ? true : false;
}

console.log(checkPositive('good')) // true;
console.log(checkPositive('hello')) // true;

Comments

0

You could also use Regular_Expressions as well to check the particular string

const checkPositive = str => /good|amazing|better/.test(str.toLowerCase());

console.log(`For bad ` +checkPositive('bad'));
console.log(`For amazing `+checkPositive('amazing'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.