Hi,
Da hier schon ein schönes Beispiel mit switch / case veröffentlich wurde, möchte ich den noch etwas funktionaleren Ansatz zeigen:
Variante 1:
const calculator = (op, n1, n2) => {
const operations = {
'*': (n1, n2) => n1 * n2,
'+': (n1, n2) => n2 + n1
};
return operationsop;
};
document.writeln(calculator("+", 3, 4));
Oder Variante 2:
const calculator2 = (op) => {
const operations = {
'*': (n1, n2) => n1 * n2,
'+': (n1, n2) => n2 + n1
};
return operations[op];
};
const add = calculator2("+");
document.writeln(add(3, 4));
document.writeln(calculator2("+")(3, 4));
Der Unterschied von Variante 1 zu switch / case ist, dass dies besser lesbar ist und einfacher umzubauen.
Variante 2 bringt dir den Vorteil, dass du die jeweilige Funktion zurückgibst. Somit kannst du diese immer wiederverwenden.
Gutes Buch um JS zu lernen:
You-Dont-Know-JS (1st Edition) https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/README.md
You-Dont-Know-JS (2nd Edition, noch nicht ganz fertig) https://github.com/getify/You-Dont-Know-JS