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
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!
switch
match
Awesome, thank you for this addition 😍👏🏻
No worries! Nice article. 👍
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. :)
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Didn't realise PHP had such nice language features these days!
Here's a JS solution for #2 just for fun:
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'smatch
!Awesome, thank you for this addition 😍👏🏻
No worries! Nice article. 👍
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. :)