4 ms·
In addition to an already mentioned early return pattern, I also often recommend switching from switch to pattern matching via an object. It has an additional
by molszanski 6y ago
In addition to an already mentioned early return pattern, I also often recommend switching from switch to pattern matching via an object.
It has an additional benefit of extracting code into data structures or making them parametric
function getArrow(direction) {
switch (direction) {
case "left":
return "<--"
case "righ":
return "-->"
default:
return "¯\\_(ツ)_/¯"
}
}
function getArrow(direction) {
const arrows = {
left: "<--",
right: "-->",
default: "¯\\_(ツ)_/¯",
}
let arrow = arrows[direction]
if (arrow) {
return arrow
} else {
return arrow.default
}
}
- hunterloftis 6y agoI use this pattern frequently, with minor changes: function getArrow(direction) { const missing = '¯\\_(ツ)_/¯' const arrows = { left: '<--', right: '-->', } return arrows[direction] || missing }
- molszanski 6y agoYes, I use it exactly like that.