Functional Programming is one of the most important concepts in Rx, basically, as long as you learn FP to get started with Rx is not difficult! Functional Programming can be said to be a prominent learning in recent years, a variety of new Functional Programming languages, other older languages are also strengthened in the new version of FP support!

RxJS (01) : RxJS%EF%BC%9A%E8%AE%A4%E8%AF%86% 20Rxjs.md)

What is Functional Programming?

functional programming icon

Functional Programming is a Programming paradigm. Just like object-oriented Programming(OOP), Functional Programming is a Programming methodology. These methodologies tell us how to think and solve problems.

To put it simply, the core idea of Functional Programming is to do operations and use function to think about problems, such as arithmetic operations like the following:

(5 + 6) - 1 * 3Copy the code

We can write it as

const add = (a, b) = > a + b
const mul = (a, b) = > a * b
const sub = (a, b) = > a - b

sub(add(5.6), mul(1.3))Copy the code

We package each operation into different functions, and use these functions to combine the results we want. This is the simplest Functional Programming.

Functional Programming Essentials

As with OOP, not all languages support FP, and a language that can support FP needs to at least comply with the feature that functions are first-class citizens.

The function is First Class.

First-class citizenship means that it has the same status as other data types, that is, functions can be assigned to variables, functions can be passed as arguments to another function, and functions can be passed back as values from one function

Functions can be assigned to variables

var hello = function() {}Copy the code

Functions can be passed in as arguments

fetch('www.google.com')
.then(function(response) {}) // function is passed to then()Copy the code

A function can be treated as a return value

var a = function(a) {
    return function(b) {
      return a + b;
    }; 
    // You can return a function
}Copy the code

Functional Programming Important features

Expression, no Statement

Functional Programming is always an Expression, not a Statement. Basic distinction between expressions and statements:

An expression is an operation that must return a value, such as performing a function

add(1.2)Copy the code
  • A statement represents some behavior, such as an assignment to a variable
a = 1;Copy the code

Sometimes expressions can also be legitimate statements, but I’m just going to do the basic thing here. For a more in-depth look at the differences, see the article Expressions versus Statements in JavaScript

Functional Programming was originally designed to handle I/O operations, and statements are usually associated with system I/O operations, so FP is naturally not a Statement.

Of course, it is impossible to completely eliminate I/O operations in practice. Functional Programming only requires that I/O operations be limited to a minimum, no unnecessary I/O behavior, and try to keep the operation process simple.

Pure Function

Pure function is a function given the same parameters that always returns the same value without any significant Side effects.

Here’s an example:

var arr = [1.2.3.4.5];

arr.slice(0.3); / / [1, 2, 3]

arr.slice(0.3); / / [1, 2, 3]

arr.slice(0.3); / / [1, 2, 3]Copy the code

Here you can see that slice returns the same value no matter how many times it executes and does nothing but return a value, so slice is a pure function.

var arr = [1.2.3.4.5];

arr.splice(0.3); / / [1, 2, 3]

arr.splice(0.3); / / [4, 5]

arr.slice(0.3); / / []Copy the code

We use splice instead, because splice affects the value of arR each time it is executed, resulting in a different result each time, which is clearly not a pure function.

Side Effect

Side Effect is when a function does something unrelated to the return value of its operation, such as modifying a global variable, changing the value of an passed parameter, or even executing console.log.

Functional Programming emphasizes that there are no Side effects, that is, functions should remain pure, only do operations and return a value, and there is no additional behavior.

Here are a few common Side effects on the front end, but not all

  • Send the HTTP request
  • Print the value or log on the screen
  • Get user input
  • Query the DOM event

Referential transparency

The previously mentioned Pure function returns the same result as long as the parameters are the same, regardless of the external environment. This feature of not relying on any external state, only on the parameters passed in is also called Referential transparency

Use parameters to save state

Thanks to the recent red Redux, I have a good example of what it means to save state with parameters. Developers who understand Redux should know that the state of Redux is made up of reducer states, and that each reducer state is saved in parameters!

function countReducer(state = 0, action) {
// ...
}Copy the code

If you’re not familiar with Redux, look at the recursion example below

function findIndex(arr, predicate, start = 0) {
    if (0 <= start && start < arr.length) {
        if (predicate(arr[start])) {
            return start;
        }
        return findIndex(arr, predicate, start+1);
    }
}
findIndex(['a'.'b'], x => x === 'b'); // Find the index of array 'b'Copy the code

Here we write findIndex to find the position of the element in the array. We deliberately add an extra parameter to findIndex to save the state of the current index.

Recursion is used here, recursion is constantly calling itself, creating multiple stack frames, which results in slow computation, which usually needs to be optimized by the compiler!

Does JS do recursive optimization? Congratulations, ES6 provides tail Call Optimization, which gives us a few tricks to make recursion more efficient!

The Functional Programming advantages

readable

When we encapsulate the data operation process through a series of functions, the code can become very concise and readable, as in the following example

[9.4].concat([8.7]) // Merge arrays
      .sort()  / / sorting
      .filter(x= > x > 5) // Filter out values greater than 5Copy the code

High maintainability

Due to features such as Pure Function, execution results are independent of external state and do nothing to the external environment, making Functional Programming better at debugging and writing unit tests.

Easy parallel/parallel processing

Functional Programming is easy to be Concurrency/Parallel. Since we basically do calculations without touching I/O, and there is no Side Effect feature, there are fewer issues like deadlock.

Today’s summary

Functional Programming today covers the basic features and advantages of Functional Programming. Nowadays, more and more libraries use the concept of FP, and JS also use more and more Functional libraries, such as Lodash, Underscore, lazy, and Ramda. Understanding the basic concepts of FP will make it easier for us to learn about other libraries and write better code. I hope you have learned something, and feel free to leave a comment below if you have any questions!