Naive functional programming in JS

Stoyan Delev
1 min readApr 29, 2017

--

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.

--

--

Stoyan Delev

web developer obsessed by making web better ( focused on web perf and a11y )