js tips for improving happiness

4. Numbers

4.1 Different Binary Representations

ES6 has added different writing formats, which should be paid attention to in the background.

29            // 10 Binary system
035            // 8 Binary 29      The original way
0o35            // 8 Binary 29      ES6 Ways
0x1d            // 16 Binary 29
0b11101            // 2 Binary 29

4.2 decimal number accurate to the specified number of digits

Round the number to the specified decimal number. Round the number to the specified decimal number using Math.round() and template literals. The second parameter decimals is omitted, and the number is rounded to an integer.

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)
round(1.345, 2)                 // 1.35
round(1.345, 1)                 // 1.3

4.3 Digital Plus 0 Operation

Thanks to netizens @JserWang@vczhan for providing this tip

Sometimes, for example, when displaying time, it is necessary to display a digit in two places. At this time, it is necessary to fill in the 0 operation. You can use slice and string's padStart method.

const addZero1 = (num, len = 2) => (`0${num}`).slice(-len)
const addZero2 = (num, len = 2) => (`${num}`).padStart( len   , '0')
addZero1(3) // 03

addZero2(32,4)  // 0032

5. Array

5.1 reduce method realizes map and filter simultaneously

Assuming there is a sequence now, you want to update each of its items (map functions) and then filter out some of them. If you use map and filter first, you need to traverse the array twice.

In the following code, we doubled the values in the sequence, and then picked out those numbers larger than 50.

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]

5.2 Number of identical items in statistical arrays

Many times, you want to count the number of iterations in an array and represent them as an object. Then you can use reduce to process this array.

The following code will count the number of each vehicle and then represent the total number as 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 }

5.3 Use deconstruction to exchange parameter values

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

let param1 = 1;
let param2 = 2;
[param1, param2] = [param2, param1];
console.log(param1) // 2
console.log(param2) // 1

Of course, there are many other ways to exchange values:

var temp = a; a = b; b = temp            
b = [a, a = b][0]                     
a = a + b; b = a - b; a = a - b        

5.4 Receiving Function Returns Multiple Results

In the following code, we get a post from / post, and then get comments from / comments. Since we are using async/await, the function places the return value in an array. And we can assign the return value to the corresponding variable directly after using array deconstruction.

async function getFullPost(){
  return await Promise.all([
     fetch('/post'),
     fetch('/comments')
  ]);
}
const [post, comments] = getFullPost();

5.5 Flatten the array to a specified depth

Using recursion, depth decreases by 1 for each depth level. Use Array.reduce() and Array.concat() to merge elements or arrays. Basically, depth equals 1 to stop recursion. If the second parameter is omitted, depth can only be tiled to a depth of 1 (single-layer tiling).

const flatten = (arr, depth = 1) =>
  depth != 1
    ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), [])
    : arr.reduce((a, v) => a.concat(v), []);
flatten([1, [2], 3, 4]);                             // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2);           // [1, 2, 3, [4, 5], 6, 7, 8]

Object Deconstruction of 5.6 Array

Arrays can also be deconstructed by objects, and the nth value of an array can be easily obtained.

const csvFileLine = '1997,John Doe,US,john@doe.com,New York';
const { 2: country, 4: state } = csvFileLine.split(',');

country            // US
state            // New Yourk

6. Objects

6.1 Use deconstruction to remove unnecessary attributes

Sometimes you don't want to keep certain object attributes, perhaps because they contain sensitive information or are just too big. You may enumerate the whole object and delete them, but in fact you simply assign these useless attributes to variables, and then use the useful parts you want to retain as the remaining parameters.

In the following code, we want to delete the _internal and tooBig parameters. We can assign them to internal and tooBig variables, and then store the remaining attributes in cleanObject for backup.

let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};

console.log(cleanObject);                         // {el1: '1', el2: '2', el3: '3'}

6.2 Deconstruction of nested objects in function parameters

In the following code, engine is an object nested in the object car. If we are interested in the vin attribute of engine, it can be easily obtained 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

7. Code Reuse

7.1 Object [key]

Although writing foo.bar as foo['bar'] is a common practice, it forms the basis for writing reusable code. Many frameworks use this approach, such as element form validation.

Consider the following simplified example of a validation function:

function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}
console.log(validate({first:'Bruce',last:'Wayne'})); // true

The above function completes the verification perfectly. But when there are many forms, validation needs to be applied, with different fields and rules. If you can build a generic validation function that is configured at run time, it's a good choice.

// object validation rules
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// universal validation function
const validate = (schema, values) => {
  for(field in schema) {
    if(schema[field].required) {
      if(!values[field]) {
        return false;
      }
    }
  }
  return true;
}
console.log(validate(schema, {first:'Bruce'})); // false
console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

Now that we have this validation function, we can reuse it in all forms without having to write custom validation functions for each form.

Links to the original text: https://mp.weixin.qq.com/s?src=11&timestamp=1570584768&ver=1901&signature=KY3nDdEdEsigZCBqgpxsLeBUQVver-VEbfTJ*DhURfPpYB-p1WVwsMxmzgNa9IajLxs2HryW2xvwsdWYKqM65KbrNCSNA-XwQvdjOgLil0R7Y*7Zh4HXPrRLMGlS4llx&new=1

Tags: Javascript Attribute

Posted on Wed, 09 Oct 2019 02:29:26 -0700 by Chetan