DEV Community

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

Collapse
 
shuckster profile image
Conan • Edited

Didn't realise PHP had such nice language features these days!

Here's a JS solution for #2 just for fun:

// Helpers
//
const memoize = (fn, cache = new Map()) =>
  x => cache.has(x)
     ? cache.get(x)
     : cache.set(x, fn(x)).get(x)

const matchMaker = lookFor => 
                   haystack => 
                   needle => 
                     lookFor(needle, haystack)

const match = matchMaker((needle, haystack) => {
  const found = haystack
    .filter(x => Array.isArray(x[0]))
    .find(x => x[0].includes(needle))
  return found !== undefined 
    ? found[1] 
    : haystack.find(x => x.length === 1)[0]
})

// Implementation
//
const fontSize = memoize(match([
  [[100, 200],        "Super Thin"],
  [[300],             "Thin"],
  [[400, 500],        "Normal"],
  [[600, 700, 800],   "Bold"],
  [[900],             "Heavy"],
  [/* default */      "Not valid"],
]))

;[100, 200, 300, 400, 500, 600, 700, 800, 900, 901]
  .forEach(size => {
    console.log(`${size} = `, fontSize(size))
  })

// 100 =  Super Thin
// 200 =  Super Thin
// 300 =  Thin
// 400 =  Normal
// 500 =  Normal
// 600 =  Bold
// 700 =  Bold
// 800 =  Bold
// 900 =  Heavy
// 901 =  Not valid
Enter fullscreen mode Exit fullscreen mode

I included a memoizer just so that it would (with usage) have the "lookup-iness" of switch, but obviously it's not quite as elegant as PHP's match!

Collapse
 
devmount profile image
Andreas

Awesome, thank you for this addition 😍👏🏻

Collapse
 
shuckster profile image
Conan

No worries! Nice article. 👍

Collapse
 
shuckster profile image
Conan • Edited

To follow this up, I've since learned about an upcoming TC39 spec on adding pattern-matching to JavaScript.

It's Stage 1 -- so a long way off -- but there are many libraries available that offer it, now including my own.

I even reused your font-size example in the README. :)