Javascript Calculator
Published on 22 Dec 2022
I decided to go a little further with the calculator exercise in Lecture 122. The obvious, defective solution is IF ELSE, but I prefer to take advantage of the fact that the parameter (string or symbol) that describe the arithmetic function. So calc1 is the beginner’s way of doing things, whereas calc2 is the kind of code that I look for:
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
return a / b;
}
function invokeMe(string, array) {
if (typeof window[string] === "function") {
return window[string].apply(null, array);
}
}
function calc1(action, a, b) {
if (action == "add") {
return add(a, b);
} else if (action == "subtract") {
return subtract(a, b);
} else if (action == "multiply") {
return multiply(a, b);
} else if (action == "divide") {
return divide(a, b);
} else {
return "Something went wrong";
}
}
function calc2(string, array) {
var actions = ["add", "subtract", "multiply", "divide"];
if (actions.includes(string)) {
return invokeMe(string, array);
} else {
console.log("not a valid action");
return null;
}
}
The key is the function invokeMe which uses a string to call a function (or invoke a method) WITHOUT USING eval.
all tags
activerecord android annoyances api apt arch array artix atom az3w backend bash blog browser bug callback career cli cloud code coding config configuration cp crud css database db design devops django email erp filter fugitive gif gist git gnome grep hebrew http ide isbn-fetcher iso javascript job search js kanban kanban\ kindle koans linux logger manjaro map markdown microservices mobi mtp neovim nodejs packages pastbin patch post python rails reduce refactoring rest routes rspec ruby scripting security sed shell sql string_replacement study tdd terminal testing version_control vim walkthrough workflow