Getting Started Functional Programming - A Case Study of Javascript

Functional programming using expressions and functions without changing the state of the data and to write a programming paradigm procedure.
By adhering to this paradigm, we can write more lucid, more resistant bug-free code. This is achieved by avoiding the use of flow control statements (for, while, break, continue , goto) to achieve, it is harder to these statements. In addition, functional programming requires us to write pure, deterministic functions that are less likely to have a bug.

? ? ? speak English

Ok.


Before starting functional programming, we need to understand what is purely a function of Kazakhstan and non-pure functions.


Pure function is fixed there will be an output for a fixed input. Moreover, they do not have any side effects to the outside world.

const add = (a, b) => a + b;

Here, add is a pure function. This is because, for a fixed value and B, the output is always the same.

const SECRET = 2019;
const getId = (a) => SECRET * a;


getId not a pure function. Because it uses a global variable SECRET. If the SECRET changes, getId same input function will return a different value. Therefore, it is not a pure function.

let id_count = 0;
const getId = () => ++id_count;

This is a non-pure function, for the following reasons: (1) that uses a non-local variable to compute its output, (2) a variable which modifies the external world, resulting in side effects.

getId()——>1

getId()——>2

getId()——>3

? ? ? The results of each call are not the same? If we debug this code could face five Mongolia B.

id_count current value is how much? What other functions are modifying id_count? Are there other functions that depend on id_count?

In order to avoid these uncertainties, making the code more robust, so we have to use the pure function.

Three principles of functional programming (important !!!)

1. Do not change the data

2. Use pure function : a fixed input always be fixed output, but also have side effects sister

Spots about the side effects are hell was it?

If we learned C language, then certainly contact

For example a = b = 50

From the perspective of the C language is concerned, the purpose is to evaluate expressions (the result of this statement is 50).

But we write this assignment expressions using fundamental purpose is to use its side effects ( own purposes C language - arithmetic effect beyond ) : set the value of a variable and b is 50.

3. Use the expression does not use statements

"Expression" (expression) is a simple arithmetic process, there is always the return value;

"Statement" (statement) is to perform an operation, there is no return value.

In other words, each step is a simple operation, but also have a return value.

Now after reading these three may not understand, but control the following example I believe you will be able to understand.

Functional programming in JavaScript

JavaScript has const keyword, which is ideal for functional programming, because it would not change the data.

Let Kankan provide some pure JavaScript functions.

Filter

See the name to know justice is to filter the array.

array.filter(condition);

This condition (filter condition) is a function that get each and then decide whether to leave it in the array. (By returning true)

const filterEven = x => x%2 === 0;  
[1, 2, 3].filter(filterEven);  
// [2]

 

Note, filterEven is a pure function. If it is impure, then the whole filter function can not be called a pure function.

Map

map of each item in the array passed to a function, and then create a new array according to the return value of the function.

array.map(mapper)

Mapper (mapper) is to get each array and returns a value as a new element of the array.

const double = x => 2 * x;  
[1, 2, 3].map(double);  
// [2, 4, 6]

Reduce

reduce to reduce the literal translation is, why is it called to reduce it, because it is the whole array into a value.

array.reduce(reducer);

reduce is a function that returns a new value (new value has continued as a result) and the results according to the existing array.

const sum = (accumulatedSum, arrayItem) => accumulatedSum + arrayItem  
[1, 2, 3].reduce(sum);
// 6

We can see this done is reduce the accumulation arrays, that process is what is it?

The first result of the existing defaults to the first element, the first parameter is the sum function (1,2), the return value is 3,

3 and as accumulatedSum, the second function call is the sum (3,3), the return value is 6.

Concat

concat splicing new element in the array based on the original to create a new array. It differs from the push (), since the push () will change the data (to add elements to the original array), thus becoming impure functions.

[1, 2].concat([3, 4])  
// [1, 2, 3, 4]

ES6 with words, can deconstruct the assignment operator ... to achieve. 

[1, 2, ...[3, 4]]

 

Simple bar, remember this syntax Oh, very common.

Object.assign

Object.assign copies the value of the given object to the new object. Because functional programming is based on immutable data, so we use it to create a new object from an existing object.

const obj = {a : 2};  
const newObj = Object.assign({}, obj);  
newObj.a = 3;  
obj.a;  
// 2

Shorthand method: (destructuring assignment for ES6 again)

const newObj = {...obj};

 

 

Create our own pure function

We can also create your own pure function. Let's do an example to copy a string n times.

const duplicate = (str, n) =>  
    n < 1 ? '' : str + duplicate(str, n-1);
duplicate('bokeyuan!', 3)  
// bokeyuan!bokeyuan!bokeyuan!

 

Higher-order functions ( Higher-the Order Functions, hereinafter referred to as theHOF )

HOF is a function accepts as a parameter a function and the function returns. Typically, they are used to add functionality to the function (similar to the Java AOP or Python decorators, have learned little about the partnership can be compared).

const withLog = (fn) => {  
    return (...args) => {  
        console.log(`calling ${fn.name}`);  
        return fn(...args);  
    };  
};

We have created a withLog HOF, it takes a function and returns a function that runs before the function will record the incoming message.

const add = (a, b) => a + b;  
const addWithLogging = withLog(add);  
addWithLogging(3, 4);  
// calling add  
// 7

withLog HOF can also be used together with other functions, it will not create any conflict, it will not write additional code. This is the beauty of the HOF.

const addWithLogging = withLog(add);  
const hype = s => s + '!!!';  
const hypeWithLogging = withLog(hype);  
hypeWithLogging('Sale');  
// calling hype  
// Sale!!!

You can simply point directly call HOF return value.

withLog(hype)('Sale'); 
// calling hype  
// Sale!!!

Currying (Currying)

Currying means that a multi-parameter function decomposed into higher-order functions. After reading this sentence you heart is visually collapse.

We also take add functions to move chestnuts.

const add = (a, b) => a + b;

When we take it curried, we rewrite it, a plurality of parameters of these functions to a plurality of distribution function, as shown below.

const add = a => {
    return b => {
        return a + b;
    };
};
add(3)(4);  
// 7

Currying advantage is memory. We can call a function in memory of some parameters, so that you can reuse them without the need to recalculate or write redundant code.

Take a look chestnuts

add(4, getOffsetNumber());  
add(6, getOffsetNumber());  
add(10, getOffsetNumber());
 
We assume that calls getOffsetNumer () function is very resource-consuming, so the above code first, resulting in a number of resource-consuming operation recalculated, the second, also had redundant code, write three times the same call. 
And if we add function after using curried, crash look.
const addOffset = add(getOffsetNumber());
addOffset(4);
addOffset(6);

This benefit would not say, it is not self-evident.

expand

We can further optimize the wording of curried function, making it look more concise.

This is because each layer is a single-line function calls return statement. Therefore, we can reconstruct it using the arrow ES6 function, as shown below.

const add = a => b => a + b;

(This can not read does not matter, the syntax is not important, focusing on understanding the meaning of currying)

Composite function (Composition)

Men have learned high school math, complex function function sets the function, is a function of the transmission output as an input to another function, to produce a combined output.

Then we talk about the application of functional programming complex functions inside. Let's getting ready material.

Range called a first function, receiving two parameters a and b, to produce an array, each of which is the number of content from a to b.

const range = (a, b) => a > b ? [] : [a, ...range(a+1, b)];

Then we come to a function called multiply, receiving an array, then put all the elements which take up tired.

const multiply = arr => arr.reduce((p, a) => p * a);

Then maybe the stuff we use to achieve factorial.

const factorial = n => multiply(range(1, n));  
factorial(5);  
// 120  
factorial(6);  
// 720

The factorial function is similar to f (x) = g (h (x)) properties, satisfying the composite function.

to sum up

Men learn the pure and impure functions functions, functional programming, a new JavaScript features as well as some of the key concepts of functional programming.
We hope this article will arouse your interest in functional programming, then mud, to try to use it in your code.
Functional programming paradigm is written in a robust well-studied through computer program. With the introduction of the ES6, JavaScript provides better than previous functional programming experience.

 

The key concept of literacy

1. Functional programming so what are the benefits? Who gave him the right! United States, San Diego!


函数式编程确保了代码中更简单的流程控制,并避免了变量和状态更改可能会给代码带来的一些不确定性,给我们造成惊喜,哦不,惊吓。函数式编程可以帮助我们避免bug并轻松理解代码。

2.ES6是啥玩意?

ES6全称ECMAScript 6是一个新版本的JavaScript,介4里妹有用过的船新版本,挤需体验三番钟,里奏会....ES6包含了许多贼酷炫的新特性像箭头函数, 常量,  害有解构赋值运算符等等等。

 

Guess you like

Origin www.cnblogs.com/flamestudio/p/11790021.html