JavaScript functional programming - Getting Started Guide

JavaScript functional programming

1, What is functional programming

**Definition: * * functional programming is a programming paradigm, which consists of function calls and function combinations.

It can be regarded as a pipeline. Data can flow from the output of one function to the input of another function, and finally output the result.

1.1 understand functional programming from examples

Requirements: the string array becomes an object array, and the person name is converted.

['john-reese', 'harold-finch', 'sameen-shaw'] 
// convert to 
[{name: 'John Reese'}, {name: 'Harold Finch'}, {name: 'Sameen Shaw'}]

Thinking of imperative programming

Process oriented, step-by-step guidance to operate.

BAD: create a bunch of temporary variables and read them from beginning to end.

Thinking of functional programming

For function transformation, the problem is solved by function combination transformation.

1. I need a function to convert String array to Object array.

2. It involves the conversion of string - > object, which needs a function to implement.

3. This function needs to be completed with two functions

  • capitalizeName: converts the name to the specified form
  • genObj: convert any type to an object
//The first character is uppercase, and the other characters are all lowercase
const capitalize = (x) => x[0].toUpperCase() + x.slice(1).toLowerCase()

//To string
const genObj = curry((key, x) => {
    let obj = {}
    obj[key] = x
    return obj
})

//Responsible for formatting names
const capitalizeName = compose(join(' '), map(capitalize), split('-'))
//Any type of object
const convert2Obj = compose(genObj('name'), capitalizeName)
//String array to Object array
const convertName = map(convert2Obj)

let ans = convertName(['john-reese', 'harold-finch', 'sameen-shaw'])
console.log(ans)//[{name: 'John Reese'},{name: 'Harold Finch'},{name: 'Sameen Shaw'}]

1.2 features of functional programming

1. Function is a first-class citizen

Functions, like other data types, are on an equal footing and can be assigned, used as parameters, and used as return values.

2. Declarative programming

State what to do, not how to do it step by step.

Benefits: high readability, we don't need to care about how to implement it.

3. Stateless and immutable data

That is, no side effects, pure function.

No side effects

Experience: for objects, do not modify them directly. Generally, some attributes are assigned and overwritten after the object is expanded.

Pure function
  • Same input, same output.
  • No side effects. (in pure functions, we cannot change the external state: modify global variables, modify parameters, etc.)
  • Independent of external state

2, Two sharp tools of functional programming

2.1 function coritization

**Function coritization: * * enables a multivariate function to receive parameters in batches. Essentially, it returns a function to accept parameters.

1. Partial function application VS coritization

The original coriolism: the unit function is returned, that is, it accepts a parameter.

Application of some functions: return functions with smaller elements and fix any element parameters.

2. Advanced coritization

The curry function used in the ready-made library is essentially a partial function application.

**Principle: * * judge whether to return the Coriolis function / result value according to the number of incoming parameters.

3. Application of coritization

Parameter reuse to improve function diversity

There is a validation method that accepts two parameters: a regular expression and a validation string.

At this time, we can generate many new functions by fixing the first parameter (called configuration), which can be used in various occasions.

2.2 function combination

Introduction to function combination

**Definition of function combination: * * multiple functions are combined into one function. (execute from right to left)

Note: single function input is required in function combination.

  • QUES: how to implement the compose function

Function combination practice

**Requirements: * * capitalize the last element of the array, assuming that the log, head, reverse and toUpperCase functions exist.

**Idea: * * after reverse, take head, toUpperCase and log.

Writing method of imperative programming (process oriented):

log(toUpperCase(head(reverse(arr))))

Object oriented writing:

arr.reverse().head().toUpperCase().log()

Writing method of functional programming

const upperLast = compose(log, toupperCase, head, reverse)

3, Practical experience in functional programming

1. Put the data to be operated at the end in Coriolis

Because our output is usually the data to be manipulated, so when we fix the previous parameters (which we can call configuration), it can become a unit function and be directly used by function combination.

const split = curry((x, str) => str.split(x));
const join = curry((x, arr) => arr.join(x));
const replaceSpaceWithComma = compose(join(','), split(' '));
const replaceCommaWithDash = compose(join('-'), split(','));

Q: What if the data to be operated is not put at the end?

**A: * * use placeholders to resolve.

The placeholder R. is provided in Ramda, Let's assume a scenario where str in split is the first parameter.

const split = curry((str,x)=>str.split(x));

const replaceSpaceWithComma = compose(join(','), split(R.__, ' '));

2. Debug of function combination

Locate the error in the function combination and temporarily output the results of the current stage with the help of trace auxiliary function.

const trace = curry((tip, x) => { console.log(tip, x); return x; });
const lastUppder = compose(toUpperCase, head, trace('after reverse'), reverse);

4, Actual test

5, Summary

Advantages of functional programming

  • The code is concise and the function reuse rate is high.
  • Readable, no hellish nesting.
  • Low error rate, emphasis on pure functions, simple testing.

Disadvantages of functional programming

  • Performance: over wrapping of methods and performance overhead of context switching.
  • Resource occupation: in order to keep the object state immutable, many new objects are created, which puts more pressure on garbage collection.
  • Recursive trap: in order to realize compose iteration, recursive operation is adopted.

Reference link

Keywords: Javascript Front-end ECMAScript

Added by ashii on Sat, 23 Oct 2021 15:36:48 +0300