JavaScript the Fun Part


functional-programming-javascript

side-effect-free-morphism


So far we have learned about five crucial concepts

  1. function as first class citizen
  2. closure
  3. currying
  4. partial application
  5. composition

Also functions and data we use should be

  1. pure function
  2. immutable data

All these seven things leads us to have side effect free morphism.

We already talked about side effect, a state change in our application that is shared between some parts of our application (= code).

Applications with many side effects are

To eliminating these problems the with the idea of function programming is to have some functions (= pure functions) that by composing them we can tackle most part of our application.

So our pure functions play an important role in this scenario.

Morphism

The term morph means: to change something from one image to another using computer animation. Oxford Dictionary.

In FP it means changing from one type to another type. It may be a different type or the same type but an operation happens here (= between type A, to type B).

The free part is obvious and refers to not having side effect. Thus the whole phrase, side effect free morphism, means: changing from one type to another type free of any side effects.

Who does the change? Pure functions.

What kind of data do we use? As much as be possible immutable data.

How can we solve our problems? Using composition.

Composition works because of what concepts or features we have?

Because of these:

  1. function as first class citizen
  2. closure
  3. currying
  4. partial application

So we talked about all the thing till this point to have a side effect free morphism. Like what we did in a few posts ago.

R.pipe(
    fs.readFileSync,                // read the file
    toString,                       // convert it to string
    R.split( newLine ),             // array of lines
    R.map( lineToWord ),            // array of array of words
    R.flatten,                      // flatten it, array of array to array
    R.filter( ignoreEmtpyItem ),    // remove empty items
    R.sort( sortByLength ),         // sort by item's length
    R.map( mapLengthToString ),     // a single string for each item
    R.reduce( arrayToString, "" ),  // everything to a single string
    log                             // print
)( filename );

Our data, when it is read from file-system, is morphed step by step till printing it using console.log. All of these functions are pure, there is no side effects, so we could solve or problem using side effect free morphism.


Update: Mon Nov 11 2019 10:10:23 GMT+0330 (Iran Standard Time)