JS commonly used functions

Various business development are inseparable from the processing of the data, however, encountered a lot of data processing are bad. This time on the need to seek the help of search engines. This method is very low efficiency, but according to the author's personality can not guarantee the taste of their own. Therefore, this text contains a common business function manual JS, such as processing time format, which is used in mobile browser, phone number, email verification, in order to improve the efficiency of your development

 

JS commonly used functions

1. Time Format

Interface ever-changing display of time, so a function of time of treatment, its importance is self-evident.

export function formatDate (oldDate, fmt) {  
  let date = new Date()  
  if (typeof oldDate === 'string' || typeof oldDate === 'number') { date = new Date(+oldDate) } else { date = oldDate } if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) } let o = { 'M+': date.getMonth() + 1, 'd+': date.getDate(), 'h+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds() } function padLeftZero (str) { return ('00' + str).substr(str.length) } for (let k in o) { if (new RegExp(`(${k})`).test(fmt)) { let str = o[k] + '' fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str)) } } return fmt }

 

formatDate accepts two parameters, oldDate type can be Date, String, Number. Because time really find many, but also very convenient, and JS is a weakly typed language, so I'll String and Number types of data as a unified timestamp to deal with now passed the time stamp. fmt is formatted type: yyyy-MM-dd hh: mm, where yyyy | MM | dd | hh | mm respectively match on | May | date | time | sub keywords. Which is free to replace the hyphen, and other keywords will only show the years can be removed. A few examples:

 

  • yyyy Year MM month dd -> 2019 on 09 May 7 Ri
  • minutes seconds hh mm -> 16 minutes 53 seconds

 

2. "day" to get a response units timestamp

Usually get three days of time, less than 12 data, the data within 24 hours, so I get up in days to obtain a time stamp function

export function setDate(num) {  return Date.now() + num * 24 * 60 * 60 * 1000}

 

Time to get a positive future time, time to get negative over time. for example

  • Time until 12 hours -> setDate (-. 5)
  • The time until 24 hours -> setDate (-1)
  • Time after three days -> setDate (3)

 

3. Get the parameters in the URL

This application needs in the era of the three framework seemingly running out, but the interview to ask or find many, look good

Simple implementation

var urlParams = new URLSearchParams('?post=1234&action=edit');
console.log(urlParams.get('action')); // "edit"

 

Looked browser support case just fine, except ie evil

Complex realization

 

function getUrlParams(param){
  // 有赖于浏览器环境, window.location.search 是浏览器函数
  // 意思是:设置或返回从问号 (?) 开始的 URL(查询部分)。       
  var query = window.location.search.substring(1);       
  var vars = query.split("&");       
  for (var i=0;i<vars.length;i++) {               
    var pair = vars[i].split("="); if(pair[0] == param){return pair[1];} } return(false); }

For example: http://xuyuechao.top?a=3&b=5&c=8888

  • getUrlParams('a') -> 3
  • getUrlParams('b') -> 5
  • getUrlParams('c') -> 8888

4. The mobile terminal determines the type of browser

BrowserInfo = {      
  isAndroid: Boolean(navigator.userAgent.match(/android/ig)),      
  isIphone: Boolean(navigator.userAgent.match(/iphone|ipod/ig)),      
  isIpad: Boolean(navigator.userAgent.match(/ipad/ig)),      
  isWeixin: Boolean(navigator.userAgent.match(/MicroMessenger/ig)),      
  isAli: Boolean(navigator.userAgent.match(/AlipayClient/ig)),
  isPhone: Boolean(/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent))
}

 

At present the main support for Android & Apple & ipad & micro-channel & Alipay & whether it is the mobile phone side.

The array of dimension reduction

Two-dimensional array

let arr = [ [1], [2], [3] ]
arr = Array.prototype.concat.apply([], arr); // [1, 2, 3]

 

Multidimensional array dimensionality reduction

let arr = [1, 2, [3], [[4]]]
arr = arr.flat(3) // [1, 2, 3, 4]

 

flat compatibility issues, the problem is not the phone side. The browser is not compatible edge. Infinity may expand to fill an array of arbitrary depth

6. deep copy

A copy of the object using the variable B, b a value change in the change will follow, which is called a shallow copy. To get a separate copy deep need to b

Easy processing

function deepClone() {
    return JSON.parse(JSON.stringify(obj)) }

 

Since it is a simple process had his shortcomings, it is mainly used above the serialization and de-serialization of JSON. The JSON does not support undefined function and therefore encounter these situations will be missing, but has been able to meet most of the cases

Complex process

Complex process requires the use of a recursive manner

function deepClone(obj) {  
  function isClass(o) {    
  if (o === null) return "Null"; if (o === undefined) return "Undefined"; return Object.prototype.toString.call(o).slice(8, -1); } var result; var oClass = isClass(obj); if (oClass === "Object") { result = {}; } else if (oClass === "Array") { result = []; } else { return obj; } for (var key in obj) { var copy = obj[key]; if (isClass(copy) == "Object") { result[key] = arguments.callee(copy);//递归调用 } else if (isClass(copy) == "Array") { result[key] = arguments.callee(copy); } else { result[key] = obj[key]; } } return result; }

 

7. & shake orifice

Image stabilization and throttle are higher-order skills, business more common situation is to search for content change message. Even without also not be able to tell the difference, but added a novice maintenance code may worship you, oh.

Shake

function debounce(func, wait) {
    let timeout;
    return function () { let context = this; let args = arguments; if (timeout) clearTimeout(timeout); timeout = setTimeout(() => { func.apply(context, args) }, wait); } }

 

Throttling

function throttle(func, wait) {
    let previous = 0;
    return function() { let now = Date.now(); let context = this; let args = arguments; if (now - previous > wait) { func.apply(context, args); previous = now; } } }

 

8. Gets an array of extremes

function smallest(array){                           
  return Math.min.apply(Math, array);             
}                                                 
function largest(array){                            
  return Math.max.apply(Math, array); } smallest([0, 1, 2.2, 3.3]); // 0 largest([0, 1, 2.2, 3.3]); // 3.3

 

Comments thank shadowless years, and then supplement this with the implementation of es6

let list = [1, 2, 3, 4, 5]
Math.max(...list) // 5
Math.min(...list) // 1

9. decimals are equal is determined

function epsEqu(x,y) {  
  return Math.abs(x - y) < Math.pow(2, -52);
}
// 举例
0.1 + 0.2 === 0.3 // false
epsEqu(0.1 + 0.2, 0.3) // true

Thank  IAmFineThanks  Number.EPSILON, Number.EPSILON === Math.pow (2, -52) provided so the above method can also be written so

function epsEqu(x,y) {  
  return Math.abs(x - y) < Number.EPSILON;
}

 

User input is decimal, binary number is stored in the computer. So the results will be biased, so we should not directly compare the non-integer, but whichever is the upper limit, the error into the calculation. Such a limit called machine epsilon, epsilon standard double precision value is 2 ^ -53 (Math.pow (2, -53))

to sum up:

Text of the code may not necessarily be optimal code if you have a better code comments are welcome.

References:

www.jianshu.com/p/c8b86b09d…

www.cnblogs.com/wxydigua/p/…

blog.csdn.net/u014607184/…

rockjins.js.org/2017/02/15/…

 

Some make more elegant JS / read tips

For engineers, the code is written again, modified many times, read more over the key outputs, readability is critical, so the importance of high-readable code is self-evident.

1. Object instead of switch / if

公共内容:
let a = 'VIP'

场景 1
if (a === 'VIP') { return 1 } else if (a === 'SVIP') { return 2 } 场景 2 switch(a) { // 感谢 红山老六 的评论指出这部分代码的 bug。现已改正 case 'VIP': return 1 case 'SVIP': return 2 } 场景 3 let obj = { VIP: 1, SVIP: 2 }

 

Here are just a way to provide a specific scene or to use your own judgment. I used more of a scene is state map Chinese meaning, such as payment status is usually taken 1, 2, 3, this value, but a list of requirements shows the corresponding Chinese state did not pay | payments | has refunds Wait

2. || and && Magical

// 场景 1
function b(a) {
  if (a) {
    return a
  } else { return '' } } // 场景 2 function b(a) { return a || '' }

The above is || usage, also called short-circuit processing. If condition is common in, but he in fact be used directly in the statement. When the value of the first argument is true it will take the first parameter when the first parameter is not a true value will take the second parameter. && and || just the opposite. The first argument is true will take a second value of the parameter

 

Guess you like

Origin www.cnblogs.com/wakbook/p/11551242.html