Write Less Do the Same

1. If multiple conditions

/ / redundancy
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {}

/ / concise
if (['abc'.'def'.'ghi'.'jkl'].includes(x)) {}
Copy the code

2. if… else…

/ / redundancy
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}

/ / concise
let test = x > 10;
Copy the code

3. Null, Undefined, Null check

/ / redundancy
if(first ! = =null|| first ! = =undefined|| first ! = =' ') {
    let second = first;
}

/ / concise
let second = first || ' ';
Copy the code

4. The foreach loop

/ / redundancy
for (var i = 0; i < testData.length; i++)
    
/ / concise
for (let i in testData)
/ / or
for (let i of testData)
Copy the code

5. Function conditional call

/ / redundancy
function test1() {
  console.log('test1');
};
function test2() {
  console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}

/ / simple
(test3 === 1? test1:test2)();
Copy the code

6. The switch conditions

/ / redundancy
switch (data) {
  case 1:
    test1();
  break;

  case 2:
    test2();
  break;

  case 3:
    test();
  break;
  // so on...
}

/ / concise
var data = {
  1: test1,
  2: test2,
  3: test
};

data[anything] && data[anything]();
Copy the code

7. Multi-line string

/ / redundancy
const data = 'abc abc abc abc abc abc\n\t'
    + 'test test,test test test test\n\t'

/ / concise
const data = `abc abc abc abc abc abc test test,test test test test`
Copy the code

8. Implicit return

/ / redundancy
function getArea(diameter) {
  return Math.PI * diameter
}

/ / concise
getArea = diameter= > (
  Math.PI * diameter;
)
Copy the code

9. Repeat the string multiple times

/ / redundancy
let test = ' '; 
for(let i = 0; i < 5; i ++) { 
  test += 'test '; 
} 

/ / concise
'test '.repeat(5);
Copy the code

10. The power on

/ / redundant math.h pow (2, 3); // simple and 2**3 // 8Copy the code

reference

  • The original – dev. To/blessingart…

  • – github.com/reng99/blog…

  • For more – github.com/reng99/blog…