-1

Is there a way to simplify the following condition?

var test = "";
var a = "NA";
var b = "valid";

answer = (v:string)=> {
     test = v!==a && v!==b; //this condition here
}

Where both v doesn't equal a or b?

I tried v!==(a&&b) but doesn't seem to be the case.

Let me know if the above is already the simplest version of the condition, Thanks!

StPaulis
  • 2,844
  • 1
  • 14
  • 24
iBlehhz
  • 566
  • 5
  • 26

3 Answers3

3
(v: string) => { 
  test = [a,b].every(x => x !== v); 
}

or

(v: string) => { 
  test = ![a,b].includes(v); 
}
StPaulis
  • 2,844
  • 1
  • 14
  • 24
2

Mathematically speaking

According to De Morgan's Law you can always invert your expression as following:

  1. (not x) and (not y) is the same as not (x or y)
  2. (not x) or (not y) is the same as not (x and y)

You have first case, where not x = v!==a and not y = v!==b, i.e. x = v === a and y = v === b. Eventually inversion in your case will look like the following:

answer = (v:string)=> {
     test = !(v === a || v === b); //this condition here
}

Note about Intellij IDEA products (WebStorm, Intellij, PyCharm, ...)

If you will put your cursor on the condition in if statement and then press Alt+Enter you can choose option "Invert 'if' condition" that will apply De Morgan's Law automatically.

MrPisarik
  • 1,260
  • 1
  • 11
  • 21
1

As an alternative, you can create an object with states:

let test = "";
let states = {
    NA: 1,
    valid: 1,
    'Not Valid': 1
}

const answer = (v) => states[v];

An example:

let test = "";
let states = {
    NA: 1,
    valid: 1,
    'Not Valid': 1
}

const answer = (v) => states[v];


const na = 'NA';
const valid = 'valid';
const notValid = 'Not Valid';
console.log(na, answer(na))
console.log(valid, answer(valid))
console.log(notValid, answer(notValid))

One of the advantages of this approach is it is not necessary to edit answer() method, just add states to states object.

StepUp
  • 36,391
  • 15
  • 88
  • 148