r/functionalprogramming • u/NoCoach5479 • Mar 13 '24
JavaScript I have written a Pattern Matching library in Javascript
A first version.
Please have a look and share your thoughts/ideas.
Thanks!
6
Upvotes
3
u/tbm206 Mar 13 '24
The Pick and Skip feature looks new to me but isn't the rest similar to lodash/ramda's
condfunction?4
u/flatmap_fplamda Mar 13 '24
I wouldn’t call your library a pattern Matching library. I would call it more like use when rather than if. I would rather use a switch statement(I add no dependencies)
Pattern matching is useful when dealing with types, otherwise the library is just a wrapper of
ifstatements and type casting all done a runtime 🤢. Furthermore, FP langs like Scala are awesome at inferring all the permutations and forcing you to handle them at compile time, that’s its main win. There is a reason JS does not have pattern matching it’s because it cannot, no types no useful pattern matching.Anyway it order to be useful, how about wrapping the function and do error handling just to provide something useful.
Maybe take a look at Structural patterns matching in python https://peps.python.org/pep-0636/
They try to optimize in the language those runtime typechecks, normally that does not scale very well and language designers made an effort to leave those checks at compile time. Because type checking in run time is very ineficient.
Try benchmark of your library against a native if, eventually your library will be order of magnitude slower and the only “benefit”will be syntax
2
u/Adventurous-Cod-287 Mar 14 '24
Take a look at effect.ts Match - a great existing pattern matching TS lib.