Home > Software engineering >  How to make a variable be a condition?
How to make a variable be a condition?

Time:10-03

I have been trying to make a variable have two values/be a condition. It's fine if this is not possible, but I would like to not have to type 68 || 39 every time I would like to check. I have tried var left = 68 || 39 and var left = 68 && 39, but neither of those work. The variable is to check an event.keyCode number. I am trying to make my first game-in-javascript. Is this possible and if so how?

CodePudding user response:

I don't believe there is a way to make a variable be a condition but what you can do is define a method that checks if the value is 69 or 39.

For example:

function valueIs69or39(valueToCheck) {
    return valueToCheck == 69 || valueToCheck == 39;
}

now you can just use if (valueIs69or39(value)) to check, and you can shorten the method name to make it easier to type.

Hope this helps!

CodePudding user response:

If you have multiple values that fulfil a condition what you really want to do is use a collection of values as your variable, instead of a single value. i.e. An array (or Set, or Map, there are many higher order collection types that are designed for different purposes)

Something like this:

let allowedValues = [ 69, 39 ];

You would then use a method to check those values:

function testValue( value ) {
    return allowedValues.includes(value)
}

Same thing with a Set (you might use a Set because it guarantees each element only appears once):

let allowedValues = new Set([ 39, 68 ])

function testValue(value) {
    return allowedValues.has(value)
}

Same thing but with a Set that is immutable (the allowed values cannot be changed dynamically):

function testValue(value) {
    const allowedValues = new Set([ 39, 68 ])
    return allowedValues.has(value)
}

console.log(testValue(10))
console.log(testValue(39))

  • Related