DEV Community

Discussion on: PHP 8 features I wish also existed in JavaScript

Collapse
 
dwarni profile image
Andreas We • Edited

You can easily replicate match behavior (actually not, see edited version):

const match = {
  100: () => "SuperThin",
  300: () => "Thin",
  400: () => "Normal",
  600: () => "Bold",
  900: () => "Heavy"
};
const fontweight = match[weight];
Enter fullscreen mode Exit fullscreen mode

Edit

As Stephen pointed out by using the above solution fontweight will contain a function.
For some reason I did not come up with an even simpler solution first:

const match = {
  100: "SuperThin",
  300: "Thin",
  400: "Normal",
  600: "Bold",
  900: "Heavy"
};
const fontweight = match[weight];
Enter fullscreen mode Exit fullscreen mode

You can also do it without having to store the object in "match":

const fontweight = {
  100: "SuperThin",
  300: "Thin",
  400: "Normal",
  600: "Bold",
  900: "Heavy"
}[weight];
Enter fullscreen mode Exit fullscreen mode

And if you need a default value you can achieve it like that:

const fontweight = {
  100: "SuperThin",
  300: "Thin",
  400: "Normal",
  600: "Bold",
  900: "Heavy"
}[weight] || "Normal";
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pris_stratton profile image
pris stratton • Edited

That’s very clever πŸ˜€

It reminds me of the guards expression in Haskell.

Collapse
 
wearypossum4770 profile image
Stephen Smith

The issue I can see with this is now the variable fontweight is a function is it not?

Collapse
 
dwarni profile image
Andreas We • Edited

No it isn't. EDIT: Sorry you are right it is a function, for some reason I was so focused on the Arrow operator on PHP that I wanted to do something similar but did not come up with the even simpler solution.

I will update my post.