preface

Believe many friends to do the front, the functional programming has heard of, more or less all of the concept of functional programming may also have heard of, this article front will speak about the features and advantages of functional programming, but won’t take up too much content, after all speak characteristics and advantages of a find a lot of articles online

The main thing of this article is to help friends who do not understand functional programming understand functional programming; Friends who understand functional programming, do not know how to use, help you analyze the application of the actual project

features

The function is first class citizen.

Functions are literally an integral part of functional programming.

Closures and higher-order functions

The concept of closures and higher-order functions is also a lot of stuff on the web. I won’t explain it here, but if you Google it, you’ll see.

The inertia calculation

This is functional programming, very common, is also very need to understand part of the functional programming, many times, are the need to do lazy computing, for example, a common online 🌰 :

// I want to do 2+3, 2+4

// The traditional way
var a = 2;
var b = 3;
var c = 4;
a + b || a + c

// Function
var calc = a= > b => a + b
var addA = calc(2)
addA(3) || addA(4)
Copy the code

In a word: in the case of doing different things, it may be based on a certain same condition

No side effects

And inert, it is also a very important functional programming a characteristic, the use of functional programming to write code that is doesn’t care about the outside variable changes in the environment, it CARES only pass, but he is not directed against any external variables to do modification, the results of the last return it back, just to pass a calculation, in an 🌰 :

// Non-functional
var a = 1;
function calc(){
    ++a
}
calc()

/ / function type
var a = 1;
function calc(num){
    return ++num
}
calc(a)
Copy the code

In a word: don’t let your functions affect external variables

Do not modify the state

The main idea of having no side effects is to not change the state, because your function just does what you want it to do

In a word, to sum up: every cause has consequences, you give me the value, I will give you the return value

conclusion

Functional programming also has several JS features that are often used, such as function scopes and scope chains, the this pointer, as well as closures and higher-order functions mentioned above. These are important points to understand in functional programming

Here is the most important before no contact, or do not understand functional programming friends, briefly talk about what is functional programming, about very rough, but the meaning of the core has probably been expressed, do not understand can leave a message, fate reply; Leave a comment if something is wrong

Case analysis

Case 1: Attribute evaluation – Formatting for attributes

In everyday work, the result that the back end gives us is not necessarily what we want, for example, in this case, we need to make a change from a_bc to hump aBc, and if it’s a small change, it’s easy to say, an if. What if there are many uncertain cases, but we also need to make a similar conversion

// Non-functional
if (str === 'a_bc') {
    str = 'a_Bc'
}

// Function
function strTransform(str) {
    return str= > str.replace(/_[a-z]{1}/g, m => m.replace('_'.' ').toLocaleUpperCase())
}
Copy the code

So it’s easy to use, and it’s always available, and a lot of people might say, well, isn’t that the way you use it all the time? Is that a function?

Depending on the situation, if you directly modify the parameters passed in, it doesn’t count; If you do the calculation with the parameters that you passed in, and you return the new value, that counts, because you’re not modifying the original data, so there are no side effects

Case 2: Functional component-tab switching

TAB, make our daily work, often use the function, for TAB, we want to make a “pure” component:

Nonfunctional programming

<! -- vue -->
<template>
    <div v-for="(item, index) in arr" @click="switchTab($event, index)">
        {{item.name}}
    </div>
</template>
<script>
export {
    data: {
        arr:[]
    },
    mounted: fcuntion() {
        this.arr = ajaxResult;
        // ajaxResult represents the result returned by the interface
    },
    methods: {
        switchTab (e, index) {
            // Processing for the current click}}}</script>
Copy the code
// react class Tab extends Components{ constructor () { super() this.arr = [] this.switchTab.bind(this) }, ComponentWillMount () {this.arr = ajaxResult}, switchTab(index) { render () { var list = this.arr.map((item, index) => <div onClick={e => this.switchTab(e, index)}>{item.name}</div>) return ( <div> {list} </div> ) } }Copy the code

I haven’t written react for a long time. This is probably a piece of pseudo code. This is a very common TAB

The writing of functional programming

<! -- vue -->
<template>
    <div v-for="(item, index) in arr" @click="callback($event, index)">
        {{item.name}}
    </div>
</template>
<script>
export {
    props: ['arr'.'callback']}</script>
Copy the code
// react
function tab ({arr, callback}) {
    return (
        <div>
            {arr.map((item, index) => <div onClick={e= > callback(e, index)>{item.name}</div>)}
        </div>)}Copy the code

You’ll find that the amount of code written in functional programming is much less. In fact, in the real world, the amount of code is not much less, maybe a little more, but not much more, but it’s very much in line with the idea of functional programming: “pure,” no side effects, no state changes

Inside the component, it only does two things, rendering and executing the callback when the corresponding button is clicked, so it doesn’t matter where it’s used, as long as it’s in the data format of the component, it’ll work. Right

Case 3: Collaboration across components – parabola

Similar to this function, the code involved here is more complex, I will not write, write more theoretical bar

First, we need to identify several characteristics of this requirement:

  • Each function needs to be broken up into different components
  • The shopping cart display function is uncertain, but whenever an item is added, it needs to be thrown into the shopping cart
  • Due to the different shopping cart display, the Angle of the parabola is different
  • Functionality is cross-component, we can’t just pass oneclassOr aidTo judge where I’m going to throw, I can’t pass oneclassOr aidTo determine whether OR not I should start flipping

These are three basic requirements, and in doing so, we use several features of functional programming: functions, closures, higher-order functions, lazy computing, and no side effects

  • So, first of all, I write a function that takes in an entry, where do I start flipping this point
  • When we receive the position of the throw, we can create a parabola out of it, but we won’tappendChildTo the page, justcreate
  • And then use a function to define the direction of your parabola, which you can use the parabolic formula, or you can use the parabolic formulacss3animationI suggest using bezier curves
  • Finally, set up a function that receives the position you want to throw

This is a parabola function, which is completely independent, without any dependence, just doing its own parabola function, regardless of who told me to throw it

Question and answer

Q: Is it good for functional programming to call functions frequently

A: Not good, but suitable for the current business scenario. In some cases, functional programming has no side effects, is clean, does not affect the original data, to ensure that in the process of cooperation, because of their own functions will not affect others

Question: Is functional or imperative programming better

Answer: with the above answer, there is no best, only the most appropriate, everyone from the beginning to the intermediate about the time, will produce a mistake, is the object-oriented writing method is very good, very cool force, than the process to use

Actually, this is a very serious mistake, when you go up, you will find, actually good or bad is directed at the scene, no one dare to say what is the best, if we want to make a special page, and then use the react or vue is the worst way, I enclose a TAB or, how do I write very well, That’s not necessary

Project page orientation, is a rapid display to the user page, we want is to display and if you’re using a framework, experience even framework of initialization, loading framework resources, you encapsulate very much initialization logic components, in fact, this time in a process, a spindle what may be a better solution

Of course, some people would say, with the speed of the Internet these days, that time is negligible, but you can’t say that some people don’t have as good an environment as we do, and we have ios8 users in our company

conclusion

I may not be online articles, in view of the functional programming theory is so clear, because it is not an article in view of the interpretation of the concept of functional programming, I was trying to help without knowing functional programming, not with friends or know, really do a lead, let everyone put the functional programming of real use to the project

Anyway, if you really want to use functional programming in your project, just remember the nature of functional programming, do it properly, don’t force it to be functional, just like in the question and answer section, you have to find the right one, not have to use what

Every good model has its existence significance. We should try to understand why each model does so and what are the advantages of doing so

conclusion

Thank you all can see here in one breath, perhaps jumping to see, this is not the point, as long as the friends who have seen understand, found their own business scenarios, there is indeed a scene can be used, that shows that I wrote this article is valuable

If there are any inaccuracies or adjustments, please point them out in time. Welcome every boss’s advice. If you point out my shortcomings, it is a step for me to grow up

Finally say with you, I also whole a public number, the content will be synchronized with the nuggets, of course, must be the first to discover gold, you can pay attention to my public number