Is JavaScript eval() function safe to use for numeric operations? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 3 days ago.
Improve this question
Please check the code below first.
const plusFn = function(){
const sign = '+'
inputUser.textContent += sign
const equalFn = function(){
const input = `${inputUser.value}`
const numbers = input.split(`${sign}`)
const result = eval(`${+numbers[0]}${sign}${+numbers[1]}`)
}
btnEqual.addEventListener('click',equalFn)
}
btnPlus.addEventListener('click',plusFn)
Let's assume our user pressed 123 and wrote it to input area, then pressed +, from now on he trigerred the plusFn which determines a specific operator and adding a new event listener for equality button. When he gives second number and presses the equality button, operating will work as upside. Is it safe to use like that?

but I couldn't think any alternative
For something as simple as your example, where you have exactly two inputs and an operator from a constrained list (just + in your example, but I'm guessing you have three others), you could use a dispatcher object or Map:
const operatons = {
"+": (a, b) => a + b,
"*": (a, b) => a * b,
"/": (a, b) => a / b,
// ...
};
// Using it...
const operation = operation[operator];
if (!operation) {
throw new Error(`Invalid operator "${operator}"`);
}
const result = operation(input1, input2);

Related

Avoid Number() for scientific notation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to do the below
Number("0.00000000000122") results in 1.22e-12
But what I need to just that number to get converted from String to Number.
console.log(Number("0.00000000000122"))
You can do it like this:
console.log(Number("0.00000000000122").toFixed(20).replace(/\.?0+$/,""));
Explanation:
toFixed() will keep the number, and replace() will remove trailing zeroes
Edit:
It seems that you want the result of Number("0.00000000000122") to BOTH be a number and also keep it string as "0.00000000000122", not its scientific display.
In that case, you can save it as a number-type variable in ts file, then display it as a string in HTML
If you want to work with precise numbers you have to work with integers.
A Number is not an integer type, it's a float so numbers are represented in memory as a float. The toString method of the number just prints out the value in memory. The integer bit and the dot location.
const scale = 18n;
const digits = 10n ** scale;
const POUND = (number) => BigInt(number) * digits;
const toPound = (number, fraction = false) => {
if (!fraction) {
return String(number / digits);
}
const str = String(number);
if (scale < 1n) {
return str;
}
return `${str.substring(0, Number(BigInt(str.length) - scale))}.${str.substr(-Number(scale))}`;
};
const a = POUND(11000);
const b = POUND(20000);
console.log('scale', String(scale));
console.log('a', toPound(a));
console.log('b', toPound(b));
console.log('mul', toPound((a * b) / digits));
console.log('add', toPound(a + b));
console.log('div', toPound(b / (a / digits), true));
console.log('sub', toPound(b - a));

miliseconds replace from 6 to 3 decimals with javascript jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need to replace 02:04.887004 to 02:04.887 with jquery or js.
Other times I have microseconds just with four decimals (02:04.8348) and I would have 02:04.834
I would use regexp to find $:[d][d].$ and then return it but with the three decimals
If the length of the string is reliable, you can just trim the unwanted characters from the string, e.g.
let time = '02:04.887004';
// If format is reliable, get first 9 characters
console.log(time.substr(0,9));
// If length might vary and number of decimals is at least 3
// Trim from end
console.log(time.slice(0, -(time.length - time.indexOf('.') - 4)))
// Trim from start
console.log(time.substr(0, time.length - time.indexOf('.') + 2));
If the format is more unreliable, you have more work to do.
You can use a regular expression or a split function or a substring on the string to format your timestring. Here is an example of the three:
const time = '02:04.887004';
const regex = /[\d]{2}:[\d]{2}\.[\d]{3}/
const formatTime = time => {
const match = time.match(regex);
return match ? match[0] : match;
}
const formatTime2 = time => {
const m = time.split(':').shift();
const s = time.split(':').pop().split('.').shift();
const ms = time.split('.').pop().substr(0,3);
return m + ':' + s + '.' + ms;
}
const formatTime3 = time => {
return time.substr(0,9);
}
console.log(formatTime(time));
console.log(formatTime2(time));
console.log(formatTime3(time));

How could i write this random number generating button/div syntax in another way? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have the following code:
// Reference to the <div> which displays the random number:
var rndDiv = document.getElementById('rndNum')
// Reference to the <button> which generates the random number:
var rndBtn = document.getElementById('rnd')
// Generating the random number through 'click' eventlistener:
rndBtn.addEventListener('click', function intRnd() {
var n = Math.floor((Math.random() * 10) + 1);
console.log(n)
rndDiv.innerHTML = n
})
how could/should i write this code differently, how would you write it? Would you use, for example, arrow functions? let instead of var? I'm just curious. Also i'm the total opposite of a 'pro'-coder, just a beginner, and would like to read your code to this solution.
Thanks for taking your time and reading my post!
Here you go ... !
IIFE
Arrow Function
Let
(function() {
let rndBtn = document.getElementById('rnd');
rndBtn.addEventListener('click', () => {
let rndDiv = document.getElementById('rndNum');
rndDiv.innerHTML = Math.floor((Math.random() * 10) + 1);
});
})();
<button id="rnd">Click</button>
<div id="rndNum"></div>
Here is another way
const randomNumGenerator = () => Math.floor((Math.random() * 10) + 1);
const randomNumDiv = document.getElementById('rndNum');
document.getElementById('rnd').addEventListener('click', () => {
randomNumDiv.innerHTML = randomNumGenerator();
});

I need to add a number from right to left in the decimal value using javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am trying to display decimal value in calculator using javascript.
if i click any buttons in the calculator, the button value added to decimal value from the right to left and it should be display in the screen.
For Eg: The default value is 0.00 if i click 2, it should be 0.02 and if i click 3, it should be 0.23 and if i click 4, it should be 2.34 and if i click 5, it should be 23.45 and so on.
You could try:
let number = 0;
// Returns the new value in case you need it to display in console
// and updates the number variable with the new value.
function addNumberRightToLeft(value) {
number = ((number * 10) + (value / 100)).toFixed(2);
return number;
}
console.log(addNumberRightToLeft(5)); // Shows '0.05' in console and updates number variable, so it is now '0.05'.
// or
addNumberRightToLeft(5); // Does not print to console but updates number variable, so it is now '0.55'.
or even use ES6 arrow functions and without side effects (as suggested by Nika):
const addNumberRightToLeft = (p, v) => ((p * 10) + (v / 100)).toFixed(2);
where p is the last value returned and v is what you want to add. In action:
let number = 0;
number = addNumberRightToLeft(number, 5); // 0.05
number = addNumberRightToLeft(number, 5); // 0.55
Like below: resultNum should be first initialize as 0.00;
function showCalc(inputNum)
{
var a = resultNum * 10.00;
var b = inputNum / 100;
resultNum = a + b;
return resultNum;
}

trying to add numbers in javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to write a program to decrypt a encrypted message. The encrypted message is a very long set of numbers ".296.294.255.268.313.278.311.270.290.305.322.252.276.286.301.305.264.301.251.269.274.311.304.
230.280.264.327.301.301.265.287.285.306.265.282.319.235.262.278.249.239.284.237.249.289.250.
282.240.256.287.303.310.314.242.302.289.268.315.264.293.261.298.310.242.253.299.278.272.333.
272.295.306.276.317.286.250.272.272.274.282.308.262.285.326.321.285.270.270.241.283.305.319.
246.263.311.299.295.315.263.304.279.286.286.299.282.285.289.298.277.292.296.282.267.245.....ect".
Each character of the message is transformed into three different numbers (eg.first character of message is '230 .280 .264' second character is '.327.301.265' ect).
so i am trying to use javascript to add the groups of three numbers and then save them as their own variable. thanks
Assuming msg has that string in it, this will split it up and add the triplets together.
const [, triplets] = msg
.split('.')
.slice(1)
.map(v => +v)
.reduce(([count, list], val, i) => {
if ((i + 1) % 3) return [count + val, list];
return [val, list.concat(count)];
}, [0, []]);
It would depend on how the data is transmitted. It looks like you could bring the data in as a string (or parse it into a string) and then use the split method to create an array of all of your numbers.
var numbers = "234.345.456.567"
var arr = numbers.split(".")
You would then loop over the array doing whatever you need for every set of three
var newArray[]
var i
for(i = 0; i < length; i += 3){
//Add values here
//Parse back to int
newArray.push("sum Value")
}
Hope this was along the lines of what you need.
Use a regular expression to match all groups of three, then map each group to the number by splitting the string by .s and adding the 3 together:
const input = '296.294.255.268.313.278.311.270.290.305.322.252.276.286.301.305.264.301.251.269.274.311.304. 230.280.264.327.301.301.265.287.285.306.265.282.319.235.262.278.249.239.284.237.249.289.250. 282.240.256.287.303.310.314.242.302.289.268.315.264.293.261.298.310.242.253.299.278.272.333. 272.295.306.276.317.286.250.272.272.274.282.308.262.285.326.321.285.270.270.241.283.305.319. 246.263.311.299.295.315.263.304.279.286.286.299.282.285.289.298.277.292.296.282.267.245';
const groupsOfThree = input.match(/\d{3}\.\d{3}\.\d{3}\./g);
const sums = groupsOfThree.map((group) => {
const nums = group.split('.').map(Number);
return nums[0] + nums[1] + nums[2];
});
console.log(sums);

Categories