JavaScript elegant writing and Sao operation

1. Judgment is empty

  • Straightforward writing
    if(a == undefined) a = [];
    
    if(params.success){
        params.success(res);
    }
  • Elegant writing
     a = a || [];
    
    params.success&&params.success(res);
    //Matters needing attention
    1,ifCannot appear inside var,=You can use elegant writing only after the assignment definition statement
    2,ifThere can be more than one method call in, but there must betrueReturn value (this usage is not meaningful)
    

Problem: when we write js code, we often encounter the situation of complex logic judgment. Usually, you can use if/else or switch to realize multiple conditional judgment, but there will be a problem. With the increase of logic complexity, if/else/switch in the code will become more and more bloated and unintelligible

2. Multi condition judgment

  • Xiao Bai writing

    var Statistics = function(){
      console.log('implement')
    }
    switch (currentTab) 
    {
       case 0:
           Statistics();
           break;
      case 1:
         Statistics();
           break;
       case 2:
           Statistics();
         break;
        case 3:
         Statistics();
         break;
    }
  • Elegant writing
    //Take the judgment condition as the attribute name of the object and the processing logic as the attribute value of the object
    var Statistics = function(){
      console.log('implement')
    }
    const comparativeTotles = new Map([
        [0,Statistics],
        [1,Statistics],
        [2,Statistics],
        [3,Statistics]
     ])
    let map = function(val){
          return comparativeTotles.get(val)
    } 
    let getMap  = map(1); //Return undefined if not found
    if(!getMap){
          console.log('No find')
    }else{
        concaozuole.log('Execution operation')
          getMap()
    }
  • if else
/**
 * Button click event
 * @param {number} status Activity status: 2kaipiao failed in 1kaipiao, 3 kaipiao succeeded, 4 commodity sold out, 5 inventory not opened
 * @param {string} identity ID: guest guest guest master
 */
const onButtonClick = (status, identity) => {
  if (identity == 'guest') {
    if (status == 1) {
      //Function processing
    } else if (status == 2) {
      //Function processing
    } else if (status == 3) {
      //Function processing
    } else if (status == 4) {
      //Function processing
    } else if (status == 5) {
      //Function processing
    } else {
      //Function processing
    }
  } else if (identity == 'master') {
    if (status == 1) {
      //Function processing
    } else if (status == 2) {
      //Function processing
    } else if (status == 3) {
      //Function processing
    } else if (status == 4) {
      //Function processing
    } else if (status == 5) {
      //Function processing
    } else {
      //Function processing
    }
  }
}
  • After finishing
//By using the characteristics of array loop, all eligible logic will be executed, so public logic and individual logic can be executed at the same time.
const functionA = ()=>{/*do sth*/}       // Separate business logic
const functionB = ()=>{/*do sth*/}       // Separate business logic
const functionC = ()=>{/*send log*/}   // Public business logic
const actions = new Map([
    ['guest_1', () => { functionA }],
    ['guest_2', () => {  functionB }],
    ['guest_3', () => { functionC }],
    ['guest_4', () => { functionA }],
    ['default', () => { functionC  }],
    //...
])
 
/**
 * Button click event
 * @param {string} identity ID: guest guest guest master
  * @param {number} status Activity status: 2kaipiao failed in 1kaipiao, 3 kaipiao succeeded, 4 commodity sold out, 5 inventory not opened
 */
const onButtonClick = (identity, status) => {
  let action = actions.get(`${identity}_${status}`) || actions.get('default')
  action.call(this)
}

3, Operation of "Sao"

1. Generate random ID

    // Generate a random alphanumeric string of length 10
    Math.random().toString(36).substring(2);

2. Update current time per second

setInterval(()=>document.body.innerHTML=new Date().toLocaleString().slice(10,18))

3. generate random 16 base color code such as "ffffff"

'#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0');

4. Return to keyboard

// Return a keyboard figure with a string
(_=>[..."`1234567890-=~~QWERTYUIOP[]\~ASDFGHJKL;'~~ZXCVBNM,./~"].map(x=>(o+=`/${b='_'.repeat(w=x<y?2:' 667699'[x=["BS","TAB","CAPS","ENTER"][p++]||'SHIFT',p])}\|`,m+=y+(x+'    ').slice(0,w)+y+y,n+=y+b+y+y,l+=' __'+b)[73]&&(k.push(l,m,n,o),l='',m=n=o=y),m=n=o=y='|',p=l=k=[])&&k.join`
`)()

5. Elegant rounding

var a = ~~2.33   ----> 2
var b = 2.33 | 0   ----> 2
var c = 2.33 >> 0   ----> 2

6. Elegant money format

1,Using regular implementation
var test1 = '1234567890'
var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
console.log(format) // 1,234,567,890
2,Using Sao operation
function formatCash(str) {
       return str.split('').reverse().reduce((prev, next, index) => {
            return ((index % 3) ? next : (next + ',')) + prev
       })
}
console.log(format) // 1,234,567,890

7. Five methods to realize value exchange

1. var temp = a; a = b; b = temp
 
2. a ^= b; b ^= a; a ^= b; (two integers are required)
 
3. b = [a, a = b][0] (with array)
 
4. [a, b] = [b, a]; (ES6, deconstruction assignment)
 
5. a = a + b; b = a - b; a = a - b

8. Realize deep copy

var b = JSON.parse(JSON.string(a))

9. Remove the decimal part

//You can do it in any of the following ways
parseInt(num)
 
~~num
 
num >> 0
 
num | 0

10. Recursive factorization


function factorial(n) {
 
  return (n > 1) ? n * f(n - 1) : n

11. Try printing


console.log(([][[]] + [])[+!![]] + ([] + {})[!+[] + !![]])
 
console.log((!(~+[]) + {})[--[~+''][+[]] * [~+[]] + ~~!+[]] + ({} + [])[[~!+[]] * ~+[]])

12. console beautification

console.info("%c Ha-ha", "color: #3190e8; font-size: 30px; font-family: sans-serif");

Last

  • If you are interested in this article, please pay attention to it

 

Tags: Programming Attribute JSON

Posted on Thu, 13 Feb 2020 10:55:52 -0500 by malec