JavaScript Library for processing operations
-
12-12-2019 - |
Question
My code dynamically generates string/number operations. The program dynamically builds something similar to the following:
"My name " + "is " + "G-Man"
"Your age is " + "21"
"5" * "5"
I want to output this:
My Name is G-Man
Your age is 21
25
I can write a library for this, but I currently am under time constraints. If anyone aware of a library that can perform equations similar to above (int + int = int), (string + int = string), etc.?
Solution
I think you probably just want to use JavaScript's built in EVAL function.
var a = eval("5 + 5");
console.log(a); // >> 10
EDIT Wow I got 2 down-votes at almost robotic speed when I answered this question ~weird, but again EVAL is probably what you want.
var a = eval("'Your age is ' + '22'");
console.log(a); // >> Your age is 22
EDIT 2 Here's a starting point for doing some quick validation of the input to make sure nothing naughty gets Eval'd.
var test1 = [
"testing"
,"+"
,"123"
];
var test2 = [
"8"
,"*"
,"5"
,"/"
,"3"
];
var test3 = [
"window.alert('bad');"
];
var test4 = [
"\"It's hard to escape things\", said "
," + "
,"Bob"
];
function supereval(arr) {
var sEval = '';
for(var i=0; i<arr.length; i++) {
if(!isNaN(parseFloat(arr[i])) && isFinite(arr[i])) { // number
sEval += arr[i];
//console.log("> number");
} else if( /^\s?[\+\/\*\-]\s?$/i.test(arr[i]) ) { // operation
sEval += arr[i];
//console.log("> operation");
} else { // string
sEval += "\"" + arr[i].replace(/"/g, '\\"') + "\"";
//console.log("> string");
}
}
console.log("DEBUG:" + sEval);
return eval(sEval);
}
console.log(supereval(test1));
console.log(supereval(test2));
console.log(supereval(test3));
console.log(supereval(test4));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow