JavaScript the Fun Part


functional-programming-javascript

data-and-function


In previous post we mapped the UNIX style of using CLIs on a Terminal to FP function chaining.

echo {a..f} | tr [:lower:] [:upper:] | tr ' ' '\n' | sort -r 
F
E
D
C
B
A

And this is what happens.

the data we have first is something like this

echo {a..f}
a b c d e f

But after going through each next step it will change to final result.

F
E
D
C
B
A

JavaScript

We can model this simply in vanilla (native) JS.

const log = console.log.bind( console );

// our data
const numbers = [ 3, 1, 4, 2, 5, 0 ];

// our steps
const plusOne = n => n + 1;
const lessThen5 = n => n < 5;
const lessToMore = ( a, b ) => a > b;

const r =
// our pipeline:
numbers.map( plusOne ).filter( lessThen5 ).sort( lessToMore );

// our result
log( r );   // [ 1, 2, 3, 4 ]

More like a pipe

If that did not really feel like a pipeline, you are right. That is why we have libraies like

These libraries are for helping us to make our code much cleaner and much like FP languages. They have many functions that each one does a specific task. Each function is like a pattern. By understanding these functions we finally have many patterns in mind that can help us declare our API and using these functions to get the job done.

Ramda.js

Here is the same operations using Ramda.js.

const R = require( "ramda" );

// our data
const numbers = [ 3, 1, 4, 2, 5, 0 ];

// our steps
const plusOne = n => n + 1;
const lessThen5 = n => n < 5;
const lessToMore = ( a, b ) => a > b;
const log = console.log.bind( console );

// our pipeline
R.pipe(
    R.map( plusOne ),
    R.filter( lessThen5 ),
    R.sort( lessToMore ),
    log
)( numbers );

// our result
// [ 1, 2, 3, 4 ]

UNIX

Because we have our data 3, 1, 4, 2, 5, 0 and we are aware of operations we simply can get the final result using some CLIs.

echo '3 1 4 2 5 0' | perl -lpe 's/\d/$&+1/eg && s/ /\n/g;' | sort | head -n 4
1
2
3
4

What is the key things to use FP?

So what are the key things to use functional programming?

  1. Having data
  2. understanding what operations we need to use

If we have these two components, then using FP is not that hard.

Readability

If you look at this portion of code.

R.pipe(
    R.map( plusOne ),
    R.filter( lessThen5 ),
    R.sort( lessToMore ),
    log
)( numbers );

you can see it is readable and easy to track to see what is happening; or what steps we have; or what flow we have.

And this is a feature in FP that we call declarative API. It has abstraction of course and we have to learn this abstractions but it pays off after understanding them.

The same is true when we use Linux's Terminal. At first it is scary to just work with plain, old commands; but after a while and understanding patterns we have, you will be able solve complex problems and scenarios very fast and easily.

In next section we will talk about declarative and imperative API.


Update: Mon Oct 21 2019 08:43:52 GMT+0330 (Iran Standard Time)