Skip to content

KelvynValle/booleval

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

booleval - Javascript boolean expression evaluator

👀 Whats that?

The main point of this small javascript project is to allow you (and me) to evaluate boolean expressions in strings in a safier way. You just have to include the library in your project and call the function "boolEval" using your expression as paramether. It's done. Your string returned a boolean result.

🤔 Why would I use it?

Well, if you need to evaluate some string boolean expressions in your project, this solution would be quite useful. Almost everyone who had to evaluate string expressions, faced the Javascript's eval and certainly get afraid of the risks that it could take to the project. As boolEval just interpret the string, you don't have to be afraid of user's injections and other vulnerabilities. And, of course, because it's free and open.

👏 Easy to implement

Step 1: Download booleval.js

After the download, just move it to your project directory.

Step 2: Paste the following in the header of your page:

<script src="booleval.js"></script>

Step 3: Use it!

To use the boolEval() function, you just have to call it freely with your boolean expression as paramether.

🤖 Examples

boolEval("10 > 20"); //returns false
boolEval("!(10 > 20)"); //returns true
boolEval("10 > 20 || 20 > 15"); //returns true
boolEval("10 > 20 && 20 > 15"); //returns false
boolEval("(10 == 20 || 20 < 30) && 5 == 5"); //returns true
boolEval("((19 != 20 && 19 == 19) || (19 < 20 && 19 != 19)) && 10 > 5"); //returns true;

But it is quite useless to eval such static expressions, right? 🤔 Yes, it is. But, of course, you can make it more dynamic using template strings or concatenating variables. For example:

Using template strings:

let a = 10;
let b = 20;
let result = boolEval(`${a} > ${b}`); //returns false

OR, concatenating:

let a = 10;
let b = 20;
let result = boolEval(a + " > " + b); //returns false

And, of course, getting expressions from user:

//user-input is the id of the input text that get expression from user
var expression = document.getElementById("user-input").value;
let result = boolEval(expression);

Maybe you could even use expressions generated by your own code:

var expression = myExpression();
let result = boolEval(expression);