DEV Community

Cover image for Pattern-Match your JavaScript with Z

Pattern-Match your JavaScript with Z

K on February 20, 2019

Cover image by Dennis Skley on Flickr Functional programming techniques seem to be rather popular these days. People are using monads in JavaScrip...
Collapse
 
joelnet profile image
JavaScript Joel

This is incredible. I have a lot of questions regarding how this is done. I use Ramda's cond quite a bit. But I really like this syntax.

I'm curious to see how this works when minified. I believe it is using some type of reflection.

Collapse
 
kayis profile image
K

It seems to use a package called js-function-reflector which transforms a function object to it's string representation and parses it again.

github.com/arrizalamin/js-function...

Collapse
 
halcaponey_35 profile image
halcaponey

and js-function-reflector uses the toString() method availaible on functions

Thread Thread
 
joelnet profile image
JavaScript Joel

the toString()

That doesn't seem like it would work for minified code as the parameter names would be uglified.

Thread Thread
 
kayis profile image
K

It works as long as you don't compile the default arguments to ES5.

Collapse
 
joelnet profile image
JavaScript Joel

One limitation I see is something like this is not possible:

import allPass from 'mojiscript/logic/allPass'
import cond from 'mojiscript/logic/cond'

const isFizz = num => num % 3 === 0
const isBuzz = num => num % 5 === 0
const isFizzBuzz = allPass ([ isFizz, isBuzz ])

const fizziness = cond ([
  [ isFizzBuzz, 'FizzBuzz' ],
  [ isFizz, 'Fizz' ],
  [ isBuzz, 'Buzz' ],
  [ () => true, x => x ]
])

fizziness(1) //=> 1
fizziness(3) //=> 'Fizz'
fizziness(5) //=> 'Buzz'
fizziness(15) //=> 'FizzBuzz'
Collapse
 
anwar_nairi profile image
Anwar

Very interesting, I would use it mostly to do validation. Looking forward to see what it becomes in the future.

Collapse
 
kayis profile image
K

Yes, I think the type-checking is the most practical feature of it, if it's exhaustive it could prevent many typical JavaScript bugs :)

Collapse
 
toastking profile image
Matt Del Signore

Yeah, in functional languages it usually replaces conditionals but javascript has a plethora of them. This is super cool though.

Collapse
 
anwar_nairi profile image
Anwar

Absolutely agree, I use Joi but it still seems not "natural enough" for me, always thought Javascript diserved something better. Here you go :)

Collapse
 
maxdevjs profile image
maxdevjs

Life's filling up with more and more z and z and... Good catch, did not know about this lib :)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
kayis profile image
K

Glad, you like it :)