Friday, February 3, 2023

the mysterious case of the switch(true) statement

 At work, the PO (who honestly probably has the best overall view of the Designers in Figma, Devs in CSS that is the heart our project) came up with some complex logic to deal fixed widths and heights vs flexbox (Figma is still at its heart a vector tool, and while it has some powerful tools like "hug" (i.e. stretch to fit your children) vs "fill" (i.e. stretch to fill your own parent) that map up sort of ok with CSS's flexbox, there can be a lot of weird edge cases.

One of the developers encouraged the PO to rewrite the nested if() statements as switch/case. But he came up with an interesting design that I hadn't heard of before, rather than

switch(someVar){
  case 'someValue1':
  break;
  case 'someValue2':
  break;
}


He did something like 

switch(true){
  case (someVar == 'someValue1' && someOtherConditional):
  break;
  case (someVar == 'someValue2' && someOtherConditional):
  break;
}

I had to set up a codepen to answer "does that even work?" but javascript being javascript, of course it does. (I suspect the older langauges like C wouldn't allow such shenanigans)

This article goes over some of the pros and cons... you can absolutely do some stuff that's more readable than a pile of nested if/else structures, and being able to run a function rather than compare to a primitive function might be useful.

No comments:

Post a Comment