Alternative to Math.pow "**" ES7 polyfill for IE11
I am trying to evaluate an expression that contains cardinality in a string like **
. those. eval("(22**3)/12*6+3/2")
... The problem is that Internet Explorer 11 won't recognize this and will not throw a syntax error. What polyfill should I use to overcome this? I am currently using Modernizr 2.6.2
.
a rough equation would be,
((1*2)*((3*(4*5)*(1+3)**(4*5))/((1+3)**(4*5)-1)-1)/6)/7
((1*2)*((3*(4*5)*(1+3)**(4*5))/((1+3)**(4*5)-1)-1)/6)/7*58+2*5
(4*5+4-5.5*5.21+14*36**2+69/0.258+2)/(12+65)
If this cannot be done, what are the possible alternatives?
source to share
You cannot polyfill statements - only library members (prototypes, constructors, properties).
Since your operation is limited to a call eval
, you can try to write your own expression parser, but that will be a lot of work.
(As an aside, you shouldn't use it eval
anyway for very good reasons that I won't be involved in this post.)
Another option (hack-ish) is to use a regex to detect trivial cases x**y
and convert them to Math.pow
:
function detectAndFixTrivialPow( expressionString ) {
var pattern = /(\w+)\*\*(\w+)/i;
var fixed = expressionString.replace( pattern, 'Math.pow($1,$2)' );
return fixed;
}
eval( detectAndFixTrivialPow( "foo**bar" ) );
source to share
You can use regex to replace occurrences **
with Math.pow()
invocations:
let expression = "(22**3)/12*6+3/2"
let processed = expression.replace(/(\w+)\*\*(\w+)/g, 'Math.pow($1,$2)');
console.log(processed);
console.log(eval(processed));
Things can get complicated if you start using nested or chained cardinality expressions.
source to share
I think you need to do some preprocessing of the input. This is how I approach it:
- Find the string "**" on the line.
- Check what's left and right.
- Extract the "complete expressions" left and right - if there is only a number - take it as is, and if there is a parenthesis - find the matching one and take everything inside as an expression.
- Replace 2 expressions with Math.pow (left, right)
source to share