11 tool methods that JavaScript must learn (avoid reinventing the wheel)

I am participating in the “Nuggets·Starting Plan”

Foreword

Two days ago, I also updated two JavaScript articles. At that time, due to time problems, I just thought about where to write, because there were only three or five sentences for technical articles, and I finished reading them in a few minutes. It was really boring. This time, take advantage of the time on Saturday and Sunday to sort it out and write as much as possible. The following is the specific implementation and detailed notes

Calculate how many days until the next birthday

Note that this is achieved with the help of moment

 getBirthdayFun(){<!-- -->
       // First get the birthday of this year
      let birthdayTime = moment(). format('YYYY-') + '12-19'
      // Use the timestamp to determine whether the current timestamp is greater than the timestamp of this year's birthday
      if (moment(). unix() >= moment(birthdayTime). unix()) {<!-- -->
        // If it is greater than that, then add another year to this year's birthday, which has reached the time to get the next birthday
        birthdayTime = moment(birthdayTime).add(1, 'y').format('YYYY-MM-DD')
      }
      // This is directly calculated (the timestamp of the next birthday - the timestamp of the current date) / (60 * 60 * 24) and the final result is XX days
      return parseInt(
        (moment(birthdayTime).unix() - moment().unix()) / (60 * 60 * 24)
      )
    }

Back to top

 // Here I take the case of vue3
    const bindTop = () => {<!-- -->
       // Method 1 This can be achieved, but the effect is not very good
       window. scrollTo(0, 0)
       document.documentElement.scrollTop = 0;
        
      // Method 2 Scrolling through the timer will be visually smoother without much lagging effect
      const timeTop = setInterval(() => {<!-- -->
        // to control his gliding distance
        document.documentElement.scrollTop = scrollTopH.value -= 50
        // Remember to clear the timer (*) when scrolling to the top
        if (scrollTopH.value <= 0) {<!-- -->
          clearInterval(timeTop)
        }
      }, 10)
    }

Copy text

 const copyText = (text) => {<!-- -->
        // clipboardData copies what is needed on the page to the clipboard
        const clipboardData = window. clipboardData
        if (clipboardData) {<!-- -->
          clipboardData. clearData()
          clipboardData.setData('Text', text)
          return true
        } else if (document.execCommand) {<!-- --> // note that document.execCommand is deprecated, but some browsers still support it, remember to check the compatibility when using it
          // Get the content to be copied by creating a dom element
          const el = document.createElement('textarea')
          el.value = text
          el.setAttribute('readonly', '')
          el.style.position = 'absolute'
          el.style.left = '-9999px'
          document.body.appendChild(el)
          el. select()
          // copy the current content to the clipboard
          document.execCommand('copy')
          // delete the el node
          document.body.removeChild(el)
          return true
        }
        return false
      }
      copyText('hello!') // ctrl + v = copyText | true

Anti-Shake/Throttling

a brief introdction

  • Anti-shake: Trigger an event frequently within a specified time, subject to the last trigger
  • Throttling: Trigger an event frequently within a specified time, only once

There are many application scenarios such as:

Anti-shake is: input search, when the user is continuously inputting content, use anti-shake to reduce the number of requests and save request resources

Throttling: The scene is generally button clicks. 10 clicks per second will initiate 10 requests. After throttling, if you click more than once in 1 second, it will only be triggered once.

Let’s implement

 // anti-shake
    // fn needs anti-shake function, delay is timer time
    function debounce(fn,delay){<!-- -->
        let timer = null? // used to save the timer
        return function () {<!-- -->
            // If the timer exists, clear the timer and restart the timer
            if(timer){<!-- -->
                clearTimeout(timeout);
            }
            //Set the timer and execute the function to be executed after the specified time
            timeout = setTimeout(() => {<!-- -->
               fn.apply(this);
            }, delay);
        }
    }
    
    // throttling
    function throttle(fn) {<!-- -->
      let timer = null; // First set a variable, when the timer is not executed, the default is null
      return function () {<!-- -->
        if (timer) return; // When the timer is not executed, the timer is always false, and there is no need to execute it later
        timer = setTimeout(() => {<!-- -->
          fn.apply(this, arguments);
           // Finally, after setTimeout is executed, set the flag to true (key)
           // Indicates that the next loop can be executed.
          timer = null;
        }, 1000);
      };
    }

Filter special characters

 function filterCharacter(str){<!-- -->
        // first set a mode
        let pattern = new RegExp("[`~!@#$^ &*()=:""'.,,?|{}':;'%,\[\ \].<>/?~!@#¥...... & amp;*() & amp;-|{ }【】';]")
        let resultStr = "";
        for (let i = 0; i < str. length; i ++ ) {<!-- -->
            // Mainly through replace, pattern rules to replace characters with empty spaces, and finally splice in resultStr
            resultStr = resultStr + str.substr(i, 1).replace(pattern, '');
        }
        // When the loop ends, return the final result resultStr
        return resultStr;
    }
    
    // example
    filterCharacter('gyaskjdhy12316789#$%^ & amp;!@#1=123,./[') // result: gyaskjdhy123167891123

Common regular judgment

 // Check 2-9 digits of text, if it does not match, it will be false, if it matches, it will be true
    const validateName = (name) => {<!-- -->
      const reg = /^[\\一-\\龥]{2,9}$/;
      return reg.test(name);
    };

    // Verify phone number
    const validatePhoneNum = (mobile) => {<!-- -->
      const reg = /^1[3,4,5,6,7,8,9]\d{9}$/;
      return reg.test(mobile);
    };

    // Check the password consisting of 6 to 18 uppercase and lowercase letters, numbers and underscores
    const validatePassword = (password) => {<!-- -->
      const reg = /^[a-zA-Z0-9_]{6,18}$/;
      return reg.test(password);
    };

Initialize the array

 // The fill() method is a new method in es6. Filling the array with the specified elements is actually initializing the array with the default content
    const arrList = Array(6).fill()
    console.log(arrList) // What is printed here is ['','','','','','']

Convert RGB to hex

 function getColorFun(r,g,b) {<!-- -->
       return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
    }
    
    getColorFun(178,232,55) // output here is #b2e837

Check if it is a function

 // Check whether it is a function In fact, it isFunction directly after the writing method, to avoid repeated writing judgment
    const isFunction = (obj) => {<!-- -->
        return typeof obj === "function" & amp; & amp; typeof obj.nodeType !== "number" & amp; & amp; typeof obj.item !== "function";
    };

Check if it is a safe array

 // Check whether it is a safe array, if not, return an empty array here with the help of the isArray method
  const safeArray = (array) => {<!-- -->
    return Array.isArray(array) ? array : []
  }

Check if the object is a safe object

 // first to determine whether the current object is a valid object
    const isVaildObject = (obj) => {<!-- -->
        return typeof obj === 'object' & amp; & amp; !Array.isArray(obj) & amp; & amp; Object.keys(obj).length
    }
    // Use the above function directly here, if it is valid, it will return itself, if it is invalid, it will return an empty object
    const safeObject = obj => isVaildObject(obj) ? obj : {<!-- -->}
    

Last

Some codes in the above case are in my separate v3 project. If you need to, you can follow me, and then ask me for information, or you can ask me for interview questions. There are all of them. If there is something unclear in the above article, please point it out, I hope it can help everyone to a certain extent, thank you for your support~