Common skills in ES6

Time:2022-1-22

Tips commonly used in ES6

  1. Mandatory parameters

ES6 provides a default parameter value mechanism, which allows you to set default values for parameters to prevent these parameters from being passed in when the function is called.

In the following example, we write a required () function as the default values for parameters a and B. This means that if one of the parameters of a or B does not pass a value at the time of call, it defaults to the required () function and throws an error.

const required = () => {throw new Error(‘Missing parameter’)};

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

add(1, 2) //3
add(1) // Error: Missing parameter.

  1. Powerful reduce

The reduce method of array is very useful. It is generally used to reduce each item in the array to a single value. But you can use it to do more.

2.1 using reduce to implement Map and filter simultaneously
Suppose there is a sequence now, and you want to update each item of it (the function of map) and then filter out a part (the function of filter). If you use map and then filter, you need to traverse the array twice.

In the following code, we double the values in the sequence and pick out those greater than 50. Have you noticed how we use reduce very efficiently to complete map and filter methods at the same time?

const numbers = [10, 20, 30, 40];
const doubledOver50 = numbers.reduce((finalList, num) => {

num = num * 2;

if (num > 50) {

finalList.push(num);

}
return finalList;
}, []);
doubledOver50; // [60, 80]
2.2 replace map and filter with reduce
If you read the above code carefully, you should understand that reduce can replace map and filter.

2.3 use reduce to match parentheses
Another use of reduce is to be able to match parentheses in a given string. For a string with parentheses, we need to know whether the number of (and) is consistent and whether (appears before).

In the following code, we can easily solve this problem by using reduce. We only need to declare a counter variable with an initial value of 0. When encountering (counter plus one, counter minus one). If the number of left and right parentheses matches, the final result is 0.

//Returns 0 if balanced.
const isParensBalanced = (str) => {
return str.split(”).reduce((counter, char) => {

if(counter < 0) { //matched ")" before "("
  return counter;
} else if(char === '(') {
  return ++counter;
} else if(char === ')') { 
  return --counter;
}  else { //matched some other char
  return counter;
}

}, 0); //<– starting value of the counter}
isParensBalanced(‘(())’) // 0 <– balanced
isParensBalanced(‘(asdfds)’) //0 <– balanced
isParensBalanced(‘(()’) // 1 <– not balanced
isParensBalanced(‘)(‘) // -1 <– not balanced
2.4 count the number of identical items in the array
Many times, you want to count the number of repeated items in the array and then represent it with an object. Then you can use the reduce method to process this array.

The following code will count the number of each type of car, and then represent the total with an object.

var cars = [‘BMW’,’Benz’, ‘Benz’, ‘Tesla’, ‘BMW’, ‘Toyota’];
var carsObj = cars.reduce(function (obj, name) {
obj[name] = obj[name] ? ++obj[name] : 1;
return obj;
}, {});
carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }
There are too many other uses of reduce. It is recommended to read the relevant code examples of MDN.

  1. Object deconstruction

3.1 delete unnecessary attributes
Sometimes you don’t want to keep some object properties, perhaps because they contain sensitive information or are just too big. You may enumerate the whole object and delete it, but in fact, you just need to assign these useless attributes to the variable, and then take the useful part you want to keep as the remaining parameters.

In the following code, we want to delete_ Internal and toobig parameters. We can assign them to internal and toobig variables, and then store the remaining attributes in cleanobject for later use.

let {_internal, tooBig, …cleanObject} = {el1: ‘1’, _internal:”secret”, tooBig:{}, el2: ‘2’, el3: ‘3’};

console.log(cleanObject); // {el1: ‘1’, el2: ‘2’, el3: ‘3’}
3.2 deconstructing nested objects in function parameters
In the following code, engine is an object nested in the car object. If we are interested in the VIN property of engine, we can easily get it by using deconstruction assignment.

var car = {
model: ‘bmw 2018’,
engine: {

v6: true,
turbo: true,
vin: 12345

}
}
const modelAndVIN = ({model, engine: {vin}}) => {
console.log(model: ${model} vin: ${vin});
}
modelAndVIN(car); // => model: bmw 2018 vin: 12345
3.3 consolidation object
ES6 brings the extension operator (…). It is generally used to deconstruct arrays, but you can also use it to deal with objects.

Next, we use the extension operator to expand a new object. The attribute value in the second object will overwrite the attribute value of the first object. For example, B and C of object2 will overwrite the same name attribute of object1.

let object1 = { a:1, b:2,c:3 }
let object2 = { b:30, c:40, d:50}
let merged = {…object1, …object2} //spread and re-add into merged
console.log(merged) // {a:1, b:30, c:40, d:50}

  1. Sets

4.1 array de duplication using set
In ES6, because set only stores unique values, you can use set to delete duplicates.

let arr = [1, 1, 2, 2, 3, 3];
let deduped = […new Set(arr)] // [1, 2, 3]
4.2 using array method for set
Using the extension operator, you can simply convert a set into an array. So you can use all the native methods of array for set.

For example, we want to perform a filter operation on the following set to obtain items greater than 3.

let mySet = new Set([1,2, 3, 4, 5]);
var filtered = […mySet].filter((x) => x > 3) // [4, 5]

  1. Array deconstruction

Sometimes you put multiple values returned by a function in an array. We can use array deconstruction to get each of these values.

5.1 numerical exchange
let param1 = 1;
let param2 = 2;
//swap and assign param1 & param2 each others values
[param1, param2] = [param2, param1];
console.log(param1) // 2
console.log(param2) // 1
5.2 receive multiple results returned by the function
In the following code, we get a post from / post and then get relevant comments in / comments. Because we use async / await, the function puts the return value in an array. After using array deconstruction, we can directly assign the return value to the corresponding variable.

async function getFullPost(){
return await Promise.all([

 fetch('/post'),
 fetch('/comments')

]);
}
const [post, comments] = getFullPost();
Transferred from:https://www.cnblogs.com/robin…