• Author: Chen Da Yu Tou
  • Making: KRISACHAN

Fish head summarizes some can improve the efficiency of the development of JS skills, these skills are very practical, feel very good, want to recommend to everyone, so there is this article.

Generate random UID

const genUid = (a)= > {
  var length = 20
  var soupLength = genUid.soup_.length
  var id = []
  for (var i = 0; i < length; i++) {
    id[i] = genUid.soup_.charAt(Math.random() * soupLength)
  }
  return id.join(' ')
}
genUid.soup_ = '! # $% () *, +, -, / :; =? @[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
genUid() / /; l`yCPc9A8IuK}? N6,%}
Copy the code

None loop Generates an array of specified length

const List = len= > [...new Array(len).keys()]
const list = List(10) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

One line of code to redo the array

const list = [1.1.2.3.6.45.8.5.4.6.5]
const uniqueList = [...new Set(list)] // [1, 2, 3, 6, 45, 8, 5, 4]
Copy the code

RGB color values generate hexadecimal color values

const rgb2Hex = rgb= > {
    let rgbList = rgb.toString().match(/\d+/g)
    let hex = The '#'
    for (let i = 0, len = rgbList.length; i < len; ++i) {
      hex += ('0' + Number(rgbList[i]).toString(16)).slice(2 -)}return hex
};
rgb2Hex('100, 50, 0') / / '# 643200'
Copy the code

Color mixing

const colourBlend = (c1, c2, ratio) = > {
    ratio = Math.max(Math.min(Number(ratio), 1), 0)
    let r1 = parseInt(c1.substring(1.3), 16)
    let g1 = parseInt(c1.substring(3.5), 16)
    let b1 = parseInt(c1.substring(5.7), 16)
    let r2 = parseInt(c2.substring(1.3), 16)
    let g2 = parseInt(c2.substring(3.5), 16)
    let b2 = parseInt(c2.substring(5.7), 16)
    let r = Math.round(r1 * (1 - ratio) + r2 * ratio)
    let g = Math.round(g1 * (1 - ratio) + g2 * ratio)
    let b = Math.round(b1 * (1 - ratio) + b2 * ratio)
    r = ('0' + (r || 0).toString(16)).slice(2 -)
    g = ('0' + (g || 0).toString(16)).slice(2 -)
    b = ('0' + (b || 0).toString(16)).slice(2 -)
    return The '#' + r + g + b
}
colourBlend('#ff0000'.'#3333ff'.0.5) // "#991a80"
Copy the code

Check if it’s prime

const mathIsPrime = n= > {
  if (n === 2 || n === 3) {
    return true
  }
  if (isNaN(n) || n <= 1 || n % 1! =0 || n % 2= =0 || n % 3= =0) {
    return false;
  }
  for (let x = 6; x <= Math.sqrt(n) + 1; x += 6) {
    if (n % (x - 1) = =0 || n % (x + 1) = =0) {
      return false}}return true
}
mathIsPrime(0) // true
Copy the code

Iterate over an array of class objects

const elements = document.querySelectorAll(selector);
[].prototype.forEach.call(elements, (el, idx, list) => {
    console.log(el) // Element node
})
Copy the code

Determining the object type

const type = data= > Object.prototype.toString.call(data).replace(/^\[object (.+)\]$/.'$1').toLowerCase()
type({}) // object
Copy the code

Optimize multi-level judgment conditions

const getScore = score= > {
    const scoreData = new Array(101).fill(0)
    .map((data, idx) = > ([idx, () => (idx < 60 ? 'Fail' : 'pass')))const scoreMap = new Map(scoreData)
    return (scoreMap.get(score) 
          ? scoreMap.get(score)() 
          : 'Unknown score')
}
getScore(30) / / don't pass the exam
Copy the code

Time formatting

const dateFormatter = (formatter, date) = > {
	date = (date ? new Date(date) : new Date)
	const Y = date.getFullYear() + ' ',
          M = date.getMonth() + 1,
          D = date.getDate(),
          H = date.getHours(),
          m = date.getMinutes(),
          s = date.getSeconds()
    return formatter.replace(/YYYY|yyyy/g, Y)
        			.replace(/YY|yy/g, Y.substr(2.2))
        			.replace(/MM/g, (M < 10 ? '0' : ' ') + M)
        			.replace(/DD/g, (D < 10 ? '0' : ' ') + D)
        			.replace(/HH|hh/g, (H < 10 ? '0' : ' ') + H)
        			.replace(/mm/g, (m < 10 ? '0' : ' ') + m)
        			.replace(/ss/g, (s < 10 ? '0' : ' ') + s)
}

dateFormatter('YYYY-MM-DD HH:mm'.'1995/02/15 plague') / / the 1995-02-15 the plague
Copy the code

Afterword.

The above ten tips are snippets of code that I often use in my daily development and can greatly reduce development time. If you’re reading this right now and have a similar tip, feel free to share it in the comments below.

If you like to discuss technology, or have any comments or suggestions on this article, you are welcome to add yu Tou wechat friends to discuss. Of course, Yu Tou also hopes to talk about life, hobbies and things with you. You can also scan your wechat account to subscribe to more exciting content.