All kinds of business development are inseparable from the processing of data, but a lot of data encountered are difficult to process. This time you need to seek the help of search engines. This method is very inefficient, and according to the author’s personality can not guarantee their own taste. Therefore, this text contains a manual of common JS business functions, such as time format processing, which mobile browser is used, mobile phone number, email verification, in order to improve your development efficiency
Common JS functions
1. Time formatting
Interface display time is variable, so the importance of a function that handles time 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 }Copy the code
FormatDate takes two arguments. OldDate can be Date, String, or Number. Because it is very convenient to use time stamps to pass time, and JS is a weakly typed language, so I will treat String and Number data as time stamps. FMT is formatted type: yyyy – MM – dd hh: MM, the yyyy MM | | dd | hh was respectively match on | | | MM | | points when the keyword. The hyphen can be replaced at will, only show the year to remove other keywords. A few examples:
-
Yyyy MM month DD -> September 7, 2019
-
Hh minute mm second -> 16 minutes 53 seconds
2. Obtain the response time stamp in days
It’s usually three days old, 12 days old, 24 hours old, so I made a function to get the timestamp in days
export function setDate(num) { return Date.now() + num * 24 * 60 * 60 * 1000}
Copy the code
A positive time gets the future time, and a negative time gets the past time. For example
-
12 hours ago time -> setDate(-.5)
-
24 hours ago time -> setDate(-1)
-
Time after 3 days -> setDate(3)
3. Obtain parameters in the URL
This demand is in the era of three frames application seems to be not much, but what is asked in the interview is quite much, it is good to know
Simple implementation
var urlParams = new URLSearchParams('? post=1234&action=edit'); console.log(urlParams.get('action')); // "edit"Copy the code
Took a look at the browser support is pretty good, except for the damned IE
Complicated to implement
Function getUrlParams(param){// depending on the browser environment, window.location.search is a browser function. The starting URL (query section). 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); }Copy the code
For example: Xuyuechao.top? a=3&b=5&c=8888
-
getUrlParams(‘a’) -> 3
-
getUrlParams(‘b’) -> 5
-
getUrlParams(‘c’) -> 8888
4. Check the browser type on the mobile phone
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))
}
Copy the code
Currently it mainly supports Android, Apple, iPad, wechat, Alipay and whether it is a mobile terminal.
5. Array dimension reduction
2 d array
let arr = [ [1], [2], [3] ] arr = Array.prototype.concat.apply([], arr); / / [1, 2, 3]Copy the code
Multidimensional array dimensionality reduction
let arr = [1, 2, [3], [[4]]]
arr = arr.flat(3) // [1, 2, 3, 4]
Copy the code
The flat has compatibility problems, but the mobile terminal is not a problem. Browser side is not compatible with Edge. Infinity expands an array of any depth
6. A deep copy
Copy object B with variable A. Changing the value in A changes the value in B. This is called a shallow copy. To make A independent of B, you need a deep copy
Simple processing
function deepClone() {
return JSON.parse(JSON.stringify(obj))
}
Copy the code
Since it is simple processing has his shortcomings, the above is mainly used JSON serialization and deserialization. JSON doesn’t support functions and undefined, so it’s missing in those cases, but it’s good enough for most cases
Complex processing
Complex processing requires a recursive approach
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; }Copy the code
7. Anti-shake & Throttle
Anti-shake and throttling belong to advanced skills, which are more common in business. Even if you don’t add it, you may not be able to tell the difference, but the new maintenance code may worship you.
Image stabilization
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); }}Copy the code
The throttle
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; }}}Copy the code
8. Get the array extremum
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]); Largest ([0, 1, 2.2, 3.3]); / / 3.3Copy the code
Thanks for the comment, and this supplement with ES6 implementation
let list = [1, 2, 3, 4, 5] Math.max(... list) // 5 Math.min(... list) // 1Copy the code
9. Check if decimals are equal
function epsEqu(x,y) { return Math.abs(x - y) < Math.pow(2, -52); } / / for 0.1 + 0.2 = = = 0.3 / / false epsEqu (0.1 + 0.2, 0.3) / / trueCopy the code
EPSILON === math.pow (2, -52
function epsEqu(x,y) {
return Math.abs(x - y) < Number.EPSILON;
}
Copy the code
The user inputs decimal numbers and the computer stores binary numbers. So it’s going to be biased, so instead of directly comparing non-integers, we’re going to take the upper limit and take the error into account. Such an upper limit is called machine Epsilon, and the standard epsilon value for double precision is 2^-53 (math.pow (2, -53))
Conclusion:
The code in this article may not be optimal, but feel free to comment if you have a better one.
References:
www.jianshu.com/p/c8b86b09d…
www.cnblogs.com/wxydigua/p/…
Blog.csdn.net/u014607184/…
Rockjins.js.org/2017/02/15/…
Some tips to make JS more elegant/readable
For engineers, code is a once-written, re-written, re-read output, and readability is critical, so highly readable code is important.
1. Replace switch/if with an object
Public content: Let a = 'VIP' scenario 1 if (a === 'VIP') {return 1} else if (a === 'SVIP') {return 2} Scenario 2 switch(a) {// Thank you Comments on this part of the code pointed out bugs. Case 'VIP': return 1 case 'SVIP': return 2} Scenario 3 let obj = {VIP: 1, SVIP: 2}Copy the code
This is just one way to do it, but it’s up to you to figure out how to use it. What I use is more of a scene is state map meaning in Chinese, for example, pay state usually get is 1, 2 and 4 of this value, but the list requires display the corresponding Chinese state Did not pay | | in the payment has been refund, etc
2. | | and use &&
{/ / scenario 1 function b (a) if (a) {return a} else {return '}} / / scenario 2 function b (a) {return a | | '}Copy the code
The use of the above is | |, also called short circuit processing. This is common in if conditions, but can also be used directly in statements. If the first argument is true, the value of the first argument is taken; if the first argument is not true, the value of the second argument is taken. && coincided with | | instead. The first argument true takes the value of the second argument
conclusion
I only want two for this part, so there’s a lot of room for optimization. I hope that the versatile netizens have comments and suggestions to make the article very strong
The full text summary
The sense of knowledge to comb and summarize a step to improve, and at the same time can less work. Unconsciously, a month has passed and I have written four articles on improving the efficiency of programming development. There are also many shortcomings in the article. For the convenience of our later discussion, you can add my wechat and bring you into the group, where we can discuss and study together and grow happily.