Naive functional programming in JS

Stoyan Delev
Apr 29, 2017 · 1 min read

A few months back I started with learning Haskell, my only goal was to learn the basics of functional programming and apply those skills to JS.
The book which I was reading taught me how to implement my own version of build into language function like map/filter/reduce usually using recursion.
After every chapter, once I made Haskell version of some function I always tried to do the same in JS and after a week I had a file with lots of nice helper functions.

Here are some patterns that I found while writing those helpers:
- recursion - instead of looping through a list using for/while, functions often call itself with n-1 elements from that list
- pattern matching - unfortunate, that is something missing in JS, so I had to replace it with if/else/switch and ES6 array destructuring
- partial application: create functions in a way that latest argument is the actual data, that helps to create functions of functions with applying partial application.

an example of Partial Application

And here are my implementations of the tree most common functions: map/filter/reduce using recursion:

an example of map
an example of filter
an example of reduce

Obviously those implementations are far away from good and well performant, however, they can learn you some basic concepts of FP.

Finally, I put all functions in a small library called NaiveFP, that is right name, those implementations are really naive but at the same time good exercise.

Check out the full list of functions https://github.com/mutebg/naive-fp/blob/master/src/index.js and let me know of something could be done better.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store