Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 24, 2021 09:10 pm GMT

FP in JS: 0x02

Functional Programming in JavaScript: Part 2

You could say that the profound enlightenment you experience when you finally get it will make learning functional programming worth it. An experience such as this will make you a better programmer for the rest of your life, whether you actually become a full-time functional programmer or not.

But were not talking about learning to meditate; were talking about learning an extremely useful tool that will make you a better programmer.

Formally speaking, what exactly are the practical advantages of using functional programming?

Advantages

Cleaner code:

Functional programs are cleaner, simpler, and smaller. This simplifies debugging, testing, and maintenance.
For example, lets say we need a function that converts a two dimensional array into a one-dimensional array. Using only imperative techniques, we could write it the following way:

function merge2dArrayIntoOne(arrays) {    var count = arrays.length;    var merged = new Array(count);    var c = 0;    for (var i = 0; i < count; ++i) {        for (var j = 0, jlen = arrays[i].length; j < jlen; ++j) {            merged[c++] = arrays[i][j];        }    }    return merged}

And using functional techniques, it could be written as follows:

varmerge2dArrayIntoOne2 = function(arrays) {    return arrays.reduce(function(p, n) {        return p.concat(n);    });};

Both of these functions take the same input and return the same output. However, the functional example is much more concise and clean.

Modularity

Functional programming forces large problems to be broken down into smaller instances of the same problem to be solved. This means that the code is more modular.
Programs that are modular are clearly specified, easier to debug, and simpler to maintain. Testing is easier because each piece of modular code can potentially be checked for correctness.

Reusability

Functional programs share a variety of common helper functions, due to the modularity of functional programming. Youll find that many of these functions can be reused for a variety of different applications.
Many of the most common functions will be covered later in this series. However, as you work as a functional programmer, you will inevitably compile your own library of little functions that can be used over and over again. For example, a well-designed function that searches through the lines of a configuration file could also be used to search through a hash table.

Reduced coupling

Coupling is the amount of dependency between modules in a program. Because the functional programmer works to write first-class, higher-order, pure functions that are completely independent of each other with no side effects on global variables, coupling is greatly reduced. Certainly, functions will unavoidably rely on each other. But modifying one function will not change another, so long as the one-to-one mapping of inputs to outputs remains correct.

Mathematically correct

This last one is on a more theoretical level. Thanks to its roots in Lambda calculus, functional programs can be mathematically proven to be correct. This is a big advantage for researchers who need to prove the growth rate, time complexity, and mathematical correctness of a program.

Lets look at Fibonaccis sequence. Although its rarely used for anything other than a proof-of-concept, it illustrates this concept quite well. The standard way of evaluating a Fibonacci sequence is to create a recursive function that expresses fibonnaci(n) = fibonnaci(n-2) + fibonnaci(n1) with a base case to return 1 when n < 2, which makes it possible to stop the recursion and begin adding up the values returned at each step in the recursive call stack.
This describes the intermediary steps involved in calculating the sequence.

var fibonacci = function(n) {    if (n < 2) {        return 1;    } else {        return fibonacci(n - 2) + fibonacci(n - 1);    }}console.log(fibonacci(8));// Output: 34

However, with the help of a library that implements a lazy execution strategy, an indefinite sequence can be generated that states the mathematical equation that defines the entire sequence of numbers. Only as many numbers as needed will be computed.

var fibonacci2 = Lazy.generate(function() {    var x = 1,        y = 1;    return function() {        var prev = x;        x = y;        y += prev;        return prev;    };}());var fibonacci2 = Lazy.generate(function() {    var x = 1,        y = 1;    return function() {        var prev = x;        x = y;        y += prev;        return prev;    };}());console.log(fibonacci2.length()); // Output: undefinedconsole.log(fibonacci2.take(12).toArray()); // Output: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]var fibonacci3 = Lazy.generate(function() {    var x = 1,        y = 1;    return function() {        var prev = x;        x = y;        y += prev;        return prev;    };}());console.log(fibonacci3.take(9).reverse().first(1).toArray()); // Output: [34]

The second example is clearly more mathematically sound. It relies on the Lazy.js library of JavaScript. There are other libraries that can help here as well, such as Sloth.js and wu.js. These will be covered later, on setting up the functional programming environment.

Functional programming in a nonfunctional world

Can functional and nonfunctional programming be mixed together? Although this is the subject of a later part, Functional & Object-oriented Programming in JavaScript, it is important to get a few things straight before we go any further.
This series is not intended to teach you how to implement an entire application that strictly adheres to the rigors of pure functional programming. Such applications are rarely appropriate outside Academia. Rather, this series will teach you how to use functional programming design strategies within your applications to complement the necessary imperative code.

For example, if you need the first four words that only contain letters out of some text, they could naively be written like this:

var words = [],    count = 0;text = myString.split(' ');for (i = 0; count < 4, i < text.length; i++) {    if (!text[i].match(/[0-9]/)) {        words = words.concat(text[i]);        count++;    }}console.log(words);

In contrast, a functional programmer might write them as follows:

var words = [];var words = myString.split(' ').filter(function(x) {    return (!x.match(/[1-9]+/));}).slice(0, 4);console.log(words);

Or, with a library of functional programming utilities, they can be simplified even further:

var words = toSequence(myString).match(/[a-zA-Z]+/).first(4);

The key to identifying functions that can be written in a more functional way is to look for loops and temporary variables, such as words and count instances in the preceding example.
We can usually do away with both temporary variables and loops by replacing them with higher-order functions, which we will explore later in this series.

On the next part, we'll have an overview about functions, their types and with examples, if you found my content helpful consider following me on twitter (@_0xf10yd) as I'll be posting stuff their too and it would great if you pull up and say hi :)


Original Link: https://dev.to/0xf10yd/fp-in-js-0x02-1li4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To