Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript user input as an actual if statement javascript

I was wondering whether it is possible to take user input as an actual if statement?
For example:
user wants to find values which are >=100&<200 in an array
I’d like to make something like this:

let array = [1,100,200]
let userInput = document.querySelector("#userInput").value // ">=100&<200"

for(let i = 0; i<array.length; i++){
  if(array[i]&userInput){ // 'array[i]>=100&<200'
    console.log(true);
  }else{
    console.log(false);
  }
}
//result [false,true,false]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let array = [1,100,200]
let userInput = ">=100&<200"

function check(userInput, x) {
  const conditions = userInput.split('&').map(c => `${x}${c}`)
  const conditionsSatisfied = conditions.map(c => eval(c))
  return conditionsSatisfied.reduce((acc,x) => acc&&x)
}

for(let i = 0; i<array.length; i++){
  if(check(userInput, array[i])){ // 'array[i]>=100&<200'
    console.log(true);
  }else{
    console.log(false);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading