I am writing a JS program, where i have a condition to make some arithmetic operations based on the input. I need to add two values if i encounter the operation type as 'add' and multiply if i get 'times' as my operator value.
I tried using basic if conditions which can solve my problem , but also gives a lot of boiler plate code. I am trying to minimise the code and optimise it more.
Here is what i tried
if (otMethod === 'add') {
if (method === 'add'){
// some computation
result = ( (num + value) + otValue);
// some more computation
}
else{
// some computation
result = ( (num * value) + otValue);
// some more computation
}
} else {
if (method === 'add'){
// some computation
result = ( (num + value) * otValue);
// some more computation
}
else{
// some computation
result = ( (num * value) * otValue);
// some more computation
}
}
In this , i had to change the OT calculation based on otMethod
and had to do arithmetic operation over num based on method value
.
What my question is , can we dynamically pass the operator itself based on the condition of method
and otMethod
, so i can reduce the number of if conditions.
Thanks in advance!
You can't pass the operator themselves but you don't need to use operators. You can just use functions instead:
function add (a,b) { return a+b }
function times (a,b) { return a*b }
var op = {
add: add,
times: times
}
result = op[otMethod](op[method](num, value),otValue);
You can make it more readable by formatting it as follows:
result = op[otMethod](
op[method](
num,
value
),
otValue
);
What this boils down to is you are executing the functions and passing the result to another function. For example, if both otMethod
and method
are add
it becomes:
result = add( add(num,value), otValue )
Putting the functions in an object allows us to use the square bracket notation to choose which function to execute. The format of the operation above actually has a formal name: it is called the Polish notation.
If you can use ES6 then the arrow function syntax makes the code really terse:
var op = {
add: (a,b) => a+b,
times: (a,b) => a*b
}
Epilogue - Polish Notation
Basically the regular notation formula
(a + b) * c
becomes
* + a b c
in Polish notation.The advantage of Polish notation is that it does not require braces to denote operator precedence and also the operator and values are naturally in function call format:
*( +(a,b), c)
.The programming language Lisp actually function like this. In Lisp
+
and*
are not operators but functions.
if (otMethod === 'add') {
result = eval( "(num " + oprMap[method] + " value) + otValue" );
} else {
result = eval( "(num " + oprMap[method] + " value) + otValue" );
}
var oprMap = {
"add" : "+",
"times" : "*"
}
Using eval you can directly put the evaluate operation taking operator from the map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With