Operator replacement "with" in strict mode - javascript

I have string value which entered user, for example the variable f.
f = "1/log(x)";
In vanilla JavaScript, i used operator with:
f = "with (Math) {" + f + "}";
The code work excellent in vanilla javascript, but i use Vue js and have problems in strict mode. I don't know how replace this operator. Who faced with this problem please answer me.
I try this:
let math = Math
math.f = f
console.log(f)
But nothing working.

Basically with is not recommended to be used because it can cause issues in programs. So what are your options?
define a bunch of globals
const sqrt = Math.sqrt
const log = Math.log
const test1 = new Function("a","return sqrt(a)")
const test2 = new Function("b","return log(b)")
console.log(test1(4))
console.log(test2(100))
Other option is to do the replacements with a reg exp
const fixMath = eq => eq.replace(/(sqrt|log|pow)/g,'Math.$1')
const test1 = new Function("a", fixMath("return sqrt(a)"))
const test2 = new Function("b", fixMath("return log(b)"))
const test3 = new Function("a", "b", fixMath("return pow(a, b)"))
const test4 = new Function("a", "b", fixMath("return sqrt(pow(a, 2) + pow(b, 2))"))
console.log(test1(4))
console.log(test2(100))
console.log(test3(10, 3))
console.log(test4(3, 3))

Related

C# gives me different result of ModPow from Java & Python. Is this a bug?

all
I am Joshua.
Currently I am developing some kind of calculation logic in C#, .NET 4.7.
And I am stuck for a couple of days when using ModPow from BigInteger class.
Finally I compared with some other languages like Javascript and Python.
Here are the codes;
C#
var _a = BigInteger.Parse("-112504099738967919768410869814860903982619354592334385300478909977139427923361560492994684609769555842111970113942123739668771370088164545697837713491001933076595596664223176568695966455489156970812960564312137880189440762210023504737301351876623478203051273064143361985681097609967600291953777514093844982210010914333130253653115287655327635099624170100570446664200407152843331467876643789736619196583683418866514683967222986915221982722110686116114379750004515841618651243098835937383564483775550060041152863597757016771967904349656600797877149977649728258675384541203748747540152406727068415700988829908215424137984927266987257127615691501812286981137284264501640480312282004988469360705007547931588660449754580929985074021203105802730617855236140743357649842847802339153126105816742502906195190402079944900015779354117203169724787481860002766072928442884322075317745510521170465176626766316916518300959480576101945671060969719420147093892605449154540004740863401759952424765321581716947920578041839", NumberStyles.Number);
var _b = BigInteger.Parse("42710288472123706107732045980552936061105504205720832439400517546130482902053491661703847614802545363376415610740434485703528101945149576942291183712758802525948559100109353863348012045024391482754729786318228709846887076811626987986636873030977565323002665497040002349699696324754471341241246091133248712513", NumberStyles.Number);
var _c = BigInteger.Parse("5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807", NumberStyles.Number);
var _modPowRes = BigInteger.ModPow(_a, _b, _c);
NumberFormatInfo _formatter = new NumberFormatInfo();
_formatter.NegativeSign = "-";
string _stringRes = _modPowRes.ToString("D", _formatter);
// -4025962189194561064516553363283375014525921961557175720338529077112971710311848366234203913802556580292548393361209331638020083844074732374616343653135077799402946400533385408838985464487221381056062706959966844828188406680815976045839849337092509291814967568127589935214307295687077940893465121894442245470126915769901660325457529592729859443914551917517655171549159468233372814554103351084536838316208603471169266662039167296594675085295938849603548128017384775032304908588861826301095512209694112961080272106412321025934327013828425487280677537982063915874200399589997896633613461631025068511458444974149152947749747984549594822000420708352393424384641432718686749229405669436317664008070112083271636922781745940251494349374415266883563753139424535520085753958356376469108498554786941521255255003415937460671624180845917463097501347690828778209895285876290213489273200505952380626734459377765095025966725691306820725825499
Javascript, I used jsbn library
var _a = new BigInteger("-112504099738967919768410869814860903982619354592334385300478909977139427923361560492994684609769555842111970113942123739668771370088164545697837713491001933076595596664223176568695966455489156970812960564312137880189440762210023504737301351876623478203051273064143361985681097609967600291953777514093844982210010914333130253653115287655327635099624170100570446664200407152843331467876643789736619196583683418866514683967222986915221982722110686116114379750004515841618651243098835937383564483775550060041152863597757016771967904349656600797877149977649728258675384541203748747540152406727068415700988829908215424137984927266987257127615691501812286981137284264501640480312282004988469360705007547931588660449754580929985074021203105802730617855236140743357649842847802339153126105816742502906195190402079944900015779354117203169724787481860002766072928442884322075317745510521170465176626766316916518300959480576101945671060969719420147093892605449154540004740863401759952424765321581716947920578041839", 10);
var _b = new BigInteger("42710288472123706107732045980552936061105504205720832439400517546130482902053491661703847614802545363376415610740434485703528101945149576942291183712758802525948559100109353863348012045024391482754729786318228709846887076811626987986636873030977565323002665497040002349699696324754471341241246091133248712513", 10);
var _c = new BigInteger("5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807", 10);
var _modPowRes = _a.modPow(_b, _c);
var _stringRes = _modPowRes.toString(10);
// 1783643806175396998275362602355826387650690265345724813364371805666764467579142495237890860674783000854825016824437046690023645956675737723594580834731857259761425187634662132104996180029411374011438919474589553364998222309255272614979511868027284402170465728908528297700102876189729595563926155962569604427283291749203673030343591516627038015511719927953742781126799972560120257074290771695973286302279629131295383214811291564651109155633319576684151577295199734593114604874743329126921653504771250132941337184148762999959335547394147714802188259839801355116944682610659081543579365393513921728510730572041617697936145453462119608425988630323921319186513104423344823774870759265115372373731593225388193828408607005773987710556891304121163609340263880054616842988101393815039937434342691332663137114581535172021453932283969024301846449291944006405969946744999443455011016318658938083030075774742259090377978078691693422518308
Python
_a = -112504099738967919768410869814860903982619354592334385300478909977139427923361560492994684609769555842111970113942123739668771370088164545697837713491001933076595596664223176568695966455489156970812960564312137880189440762210023504737301351876623478203051273064143361985681097609967600291953777514093844982210010914333130253653115287655327635099624170100570446664200407152843331467876643789736619196583683418866514683967222986915221982722110686116114379750004515841618651243098835937383564483775550060041152863597757016771967904349656600797877149977649728258675384541203748747540152406727068415700988829908215424137984927266987257127615691501812286981137284264501640480312282004988469360705007547931588660449754580929985074021203105802730617855236140743357649842847802339153126105816742502906195190402079944900015779354117203169724787481860002766072928442884322075317745510521170465176626766316916518300959480576101945671060969719420147093892605449154540004740863401759952424765321581716947920578041839
_b = 42710288472123706107732045980552936061105504205720832439400517546130482902053491661703847614802545363376415610740434485703528101945149576942291183712758802525948559100109353863348012045024391482754729786318228709846887076811626987986636873030977565323002665497040002349699696324754471341241246091133248712513
_c = 5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807
_modPowRes = pow(_a, _b, _c)
print(_modPowRes)
#1783643806175396998275362602355826387650690265345724813364371805666764467579142495237890860674783000854825016824437046690023645956675737723594580834731857259761425187634662132104996180029411374011438919474589553364998222309255272614979511868027284402170465728908528297700102876189729595563926155962569604427283291749203673030343591516627038015511719927953742781126799972560120257074290771695973286302279629131295383214811291564651109155633319576684151577295199734593114604874743329126921653504771250132941337184148762999959335547394147714802188259839801355116944682610659081543579365393513921728510730572041617697936145453462119608425988630323921319186513104423344823774870759265115372373731593225388193828408607005773987710556891304121163609340263880054616842988101393815039937434342691332663137114581535172021453932283969024301846449291944006405969946744999443455011016318658938083030075774742259090377978078691693422518308
As you can see, all the consant valus _a, _b and _c are the same.
But only C# gives me the different result of ModPow.
I have tried smaller numbers, then C# gives me the same result as other languages.
I have tried to run my unit test project as x64, x86 and AnyCpu on platform target.
But the result is the same.
Can somebody explain why this is happening?
Python and C# have different definitions of Mod. Python uses the mathematical definition of mod (the result is always a non-negative number) while C# returns a value with the same sign as you started with.
You'll notice that the difference between C#'s answer and Python's answer is precisely the modulus. In effect, both are returning the same value, but a different representation of it.
>>> x # result returned by C#
-4025962189194561064516553363283375014525921961557175720338529077112971710311848366234203913802556580292548393361209331638020083844074732374616343653135077799402946400533385408838985464487221381056062706959966844828188406680815976045839849337092509291814967568127589935214307295687077940893465121894442245470126915769901660325457529592729859443914551917517655171549159468233372814554103351084536838316208603471169266662039167296594675085295938849603548128017384775032304908588861826301095512209694112961080272106412321025934327013828425487280677537982063915874200399589997896633613461631025068511458444974149152947749747984549594822000420708352393424384641432718686749229405669436317664008070112083271636922781745940251494349374415266883563753139424535520085753958356376469108498554786941521255255003415937460671624180845917463097501347690828778209895285876290213489273200505952380626734459377765095025966725691306820725825499
>>> y # result returned by Python
1783643806175396998275362602355826387650690265345724813364371805666764467579142495237890860674783000854825016824437046690023645956675737723594580834731857259761425187634662132104996180029411374011438919474589553364998222309255272614979511868027284402170465728908528297700102876189729595563926155962569604427283291749203673030343591516627038015511719927953742781126799972560120257074290771695973286302279629131295383214811291564651109155633319576684151577295199734593114604874743329126921653504771250132941337184148762999959335547394147714802188259839801355116944682610659081543579365393513921728510730572041617697936145453462119608425988630323921319186513104423344823774870759265115372373731593225388193828408607005773987710556891304121163609340263880054616842988101393815039937434342691332663137114581535172021453932283969024301846449291944006405969946744999443455011016318658938083030075774742259090377978078691693422518308
>>> y - x # your modulus
5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807

Is it possible to construct a string in Javascript which has 'variables' built in?

I am working on a PDF with some scripting, and I am applying code to fields using the console and some simple loops to save on repeated efforts. In some cases, I am applying a custom calculation script to a field where one integer needs to change from one field to the next. If all the scripts were the same, I would run this in the debugger console:
var s = "if(this.getField(\"Span A\").value >= 60){\n\
event.value = Math.round(((this.getField(\"Span A\").value*41500 - 1674500)/233));\n\
}else{\n\
event.value = Math.round((this.getField(\"Span A\").value*3500/60));\n\
}";
for (var i = 0; i < this.numFields; i++){
var f = this.getField(getNthFieldName(i));
if(f.name.match(/quant a/i) != null){
var n = f.name.match(/\d/g);
f.setAction("Calculate", s);
}
}
I have many 'Quant' fields, and each group (A, B, etc) will have a similar calculation. The fields are name "Quant A1", "Quant A2" etc. Quant A1 needs to calculate with the input from Span A1.
In the above script, it would be really cool if I could have a variable within the script string that I can pass a value (n) to be plugged in to the string, essentially the same way a function call works.
Is this possible?
Here is my fantasy version of what I imagine it could look like (this is just to further explain my intent; I don't think this would actually work this way):
var s(x) = "if(this.getField(\"Span A\""x").value >= 60){\n\
event.value = Math.round(((this.getField(\"Span A\""x").value*41500 - 1674500)/233));\n\
}else{\n\
event.value = Math.round((this.getField(\"Span A\""x").value*3500/60));\n\
}";
for (var i = 0; i < this.numFields; i++){
var f = this.getField(getNthFieldName(i));
if(f.name.match(/quant a/i) != null){
var n = f.name.match(/\d/g);
f.setAction("Calculate", s(n));
}
}
You could use string litterals if you're useing ES6 and higher.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals?retiredLocale=nl
const greetings = "I'm a variable!";
let string = `Hi! this is a variable: ${greetings}`;
console.log(string);
Otherwise concatenate it with the + operator.
If I understand correctly your question. I think you want to use template literals.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Use backticks instead of " or ' to insert your variables inside a string.
const a ='Cheese'
const b= 'is Delicious'
${a} ${b} will output 'Cheese is Delicious'

Formulation Formatting

I want to save my formulas to SQL and use it in both the controller side and javascript side on my .net core project.
{H}+({FA}*2)+{VW}
Formulas are like this format. I want to change values of H, FA and VW with numbers.
string str2 = "{H}+({FA}*2)+{VW}";
string str3 = string.Format(str2, 60, 10, 20);
string value = new DataTable().Compute(str, null).ToString();
I can calculate like this on the controller side. (If there is a better way for it i can get advice too.)
I need to do on JavaScript side too. What should I do?
EDIT;
Btw C# code doesn't work, here is the working one i need a modular thing but i don't know how to do it.
var H = "150";
var VW = "200";
var FA = "20";
string str = $"{H}+{VW}*2";
string value = new DataTable().Compute(str, null).ToString();
I can use string.replace but I've 26 variable and will be complex. I'm adding more examples to formulas.
string formula1 = {H}+({FA}*2)+{VW};
string formula2 = {W}+({FA}*2)+{HW};
string formula3 = {FA}*2+{GFH}-{MTF};
string formula4 = {VSP}/{FA}+{GFV}*(A+B+C);
string formula5 = {TH}+{W}*2+{FT}*2;
***EDIT2:
I'm thinking about to use this on C# side.
public void CalculateTest()
{
List<varKeyDto> varKeys = new List<varKeyDto>(){
new varKeyDto(){
Variable = "H",
Value ="150"
},
new varKeyDto(){
Variable = "VW",
Value ="200"
},
new varKeyDto(){
Variable = "FA",
Value ="20"
},
};
string formula = "{H}+({FA}*2)+{VW}";
string cmptd = ReturnFormula(formula, varKeys);
}
public string ReturnFormula(string formula, List<varKeyDto> varKeys)
{
string formulaString = formula;
foreach (var varKey in varKeys)
{
formulaString = formulaString.Replace("{" + varKey.Variable + "}", varKey.Value);
}
string value = new DataTable().Compute(formulaString, null).ToString();
return value;
}
You could process the string to extract the variable names and make it valid JavaScript code and use all that to create a Function, here is an example:
const str = '{H}+({FA}*2)+{VW}';
const vars = str.match(/{[A-Z]+}/g).map(v => v.replace(/[{}]/g, ''));
const fnBody = str.replace(/[{}]/g, '');
const fn = new Function(...vars, `return ${fnBody}`);
const result = fn(60, 10, 20);
console.log(result);
The generated function looks something like this:
function (H, FA, VW) {
return H+(FA*2)+VW
}
You cannot format string with such custom literals, they have to be like - {0} {1} {2} and so on.
You can use .Replace instead -
var formulaString = formula.Replace("{H}", "1").Replace("{FA}", "2").Replace("{VW}", "3");
string value = new DataTable().Compute(formulaString, null).ToString();
In javascript you can use .replaceAll-
var formula = "{H}+({FA}*2)+{VW}";
var formulaString = formula.replaceAll("{H}", 1).replaceAll("{FA}", 2).replaceAll("{VW}", 3)
console.log(eval(formulaString));

How custom tag function work with tagged template string in JavaScript?

Actually there is no error, just want know how exactly in JavaScript this tag call as a function and get the string in front of it, in other words want to know how exactly the mentioned code work.
This line is my main question:
let str = tag`My age is ${a + b} and I love ${c}`;
how the tag work as a function in here.
let tag = function (strings, ...values) {
let result = "";
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
result += values[i];
}
}
return result;
};
let a = 20;
let b = 12;
let c = "JavaScript";
let str = tag`My age is ${a + b} and I love ${c}`;
console.log(str);
the output is correct which is:
My age is 32 and I love JavaScript
This syntax:
let str = tag`My age is ${a + b} and I love ${c}`;
is described here on MDN. These are called "tagged templates". They allow you to add custom function logic that can affect how the template literal result is constructed and the template function gets access to the elements of the parsed template string.
In that above linked MDN reference there are multiple examples of different ways of using tagged templates.

Is there a JavaScript equivalent of rubys "#{}" sequences?

Is there a better way to build strings in JavaScript than doing string concatination?
It would make my code cleaner if I could do something like ruby where you can expand variables in a string instead of doing lots of "foo" + bar + "baz".
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
console.log("{0} bar {1}.".format("foo","baz"));
Will produce:
"foo bar baz"
Chris Nielsen has provided a pure-JavaScript solution in this answer:
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));
You could also use CoffeScript, which is a language that compiles to JavaScript. It supports string interpolation:
author = "Wittgenstein"
quote = "A picture is a fact. -- #{ author }"
sorry guys but all this is not very the ruby way, here is a basic p equivalent, sorry for the eval, that surely can be done better..
if you just want the concatenation, just replace the document.write by return in the first solution
function p(str){
document.write(str.replace(/#{(\w)}/g, function(match, s){return eval(s)})+"<br>");
}
String.prototype.p = function() {
return this.replace(/#{(\w)}/g, function(match, s){return eval(s)})+"<br>";
};
var f="foo", b="bar"
p("#{f} #{b}")
document.write("#{f} #{b}".p());
=> foo bar
=> foo bar
EDIT: i added a prototype version, had some difficulties with that one
var myStr = [];
myStr.push('something')
console.log(myStr.join(""))
If you deal with lots of strings then using an array where you push the string parts and at the end join them (with an empty string as delimiter) seems to be the most efficient across platforms.
"Is there a JavaScript equivalent of rubys “#{}” sequences?"
With respect to an equivalent, no. JavaScript natively does not have string interpolation. Though you could use a function to replicate it to some degree.
pylover's answer will give you something like what you want.
You might also look into CoffeeScript, which is a nice language that compiles to JavaScript and has string interpolation, among other (perhaps too many) features.
It is called syntactic sugar.
var a = 2;
var b = 4;
var c = "together";
var text = `Add ${a*b} elements ${c}.`;
console.log(text)
// "Add 8 elements together." (515,988,604 op/sec)
vs.
var text = "Add" + " " + a*b + " " + "elements" + " " + c + ".";
console.log(text)
// "Add 8 elements together." (511,188,184 op/sec 0.73% slower)
First method is faster and better to read.
Performance tested here: JSPerf string test

Categories