I’m currently working on a scientific calculator project, and figured instead of if else chaining I could create an object to store the functions as properties, to massively cut down on code and also not violate DRY heavily.
const calcFunctions = {
ce: console.log("ce"),
"x^2": square(),
radic: Math.sqrt(expression),
log: Math.log(expression),
cos: Math.cos(expression),
sin: Math.sin(expression),
tan: Math.tan(expression),
exp: Math.exp(expression),
"=": console.log("="),
undefined: console.log("undefined"),
};
What I am wondering is, is there a way to compare the statement (if this string is a key do this) and then extract the value from that statement and use it as an expression.
eg.
value = "tan"
If (calcfunctions.hasOwnProperty(value)) {
expression = Math.tan(expression) // I want it to pull the value from the key:value of tan
}
So far I have managed to get it to log a statement to the console IF it finds the key in the object, but beyond this I am lost.
if (value !== undefined) {
expression = "";
ans.value = 0;
}
if (calcFunctions.hasOwnProperty(value)) {
console.log(`${value} exists`);
}
Any insight would be appreciated.
EDIT: FOR ADDITIONAL CONTEXT
The Value
is being gotten from an HTML element, when i click on the "calculator button" it’s using an event listener and capturing the value
const value = event.target.dataset["value"]
The Expression
This is the final number or sum that goes into the calculator input field, originally project used if else chaining, so we checked if value is === "x" expression = y
else if (value == "cos") {
expression = Math.cos(expression);
}
Have tried using various suggestions found on stack overflow about using different methods however it mostly ends in undefined being returned. In the few cases it has not been undefined it has been a function does not exist error
I have also followed several tutorials but they are unfortunately not what i needed
2
Answers
First, you need to update your
calcFunctions
object to:This is an object that stores references to certain Math functions.
Next, once we have the
value
(operation to perform) andx
(number on which to perform the operation), we do like:First of all
doesn’t make too much sense, because you are not assigning functions to the properties, but results of function calls (which may even throw errors, depending on whether
expression
is defined somewhere or not). If you want your object to contain functions do it like thisThen you can do
or even simpler