1. isStatic: Detect whether the data is the original data except symbol
function isStatic(value) { return( typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'undefined' || value === null ) }
2. isPrimitive: Detect whether the data is the original data
function isPrimitive(value) { return isStatic(value) || typeof value === 'symbol' }
3. isObject: determine whether the data is a reference type of data (for example: arrays, functions, objects, regexes, new Number(0), and new String(''))
function isObject(value) { let type = typeof value; return value != null && (type == 'object' || type == 'function'); }
4. isObjectLike: Check whether value is a class object. If a value is a class object, it should not be null, and the result after typeof is "object"
function isObjectLike(value) { return value != null && typeof value == 'object'; }
5. getRawType: Get the data type, and return the result as Number, String, Object, Array, etc.
function getRawType(value) { return (value).slice(8, -1) } //getoRawType([]) ==> Array
6. isPlainObject: determine whether the data is Object type data
function isPlainObject(obj) { return (obj) === '[object Object]' }
7. isArray: determine whether the data is an array type data
function isArray(arr) { return (arr) === '[object Array]' }
Mount isArray on Array
= || isArray;
8. isRegExp: determine whether the data is a regular object
function isRegExp(value) { return (value) === '[object RegExp]' }
9. isDate: determine whether the data is a time object
function isDate(value) { return (value) === '[object Date]' }
10. isNative: determine whether value is a built-in function in the browser
The main code block after the built-in function toString is [native code], while the non-built-in function is related code, so non-built-in functions can be copied (after toString, the head and tail are pinched and then turned from Function)
function isNative(value) { return typeof value === 'function' && /native code/.test(()) }
11. isFunction: Check whether the value is a function
function isFunction(value) { return (value) === '[object Function]' }
12. isLength: Check whether the value is the valid class array length
function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= Number.MAX_SAFE_INTEGER; }
13. isArrayLike: Check whether the value is a class array
If a value is considered an array of classes, it is not a function and is an integer greater than or equal to 0, less than or equal to Number.MAX_SAFE_INTEGER. Here strings will also be treated as class arrays
function isArrayLike(value) { return value != null && isLength() && !isFunction(value); }
14. isEmpty: Check whether the value is empty
If it is null, return true directly; if it is a class array, judge the data length; if it is an Object object, judge whether it has attributes; if it is other data, return false directly (can also change to return true)
function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value)) { return !; }else if(isPlainObject(value)){ for (let key in value) { if ((value, key)) { return false; } } return true; } return false; }
15. cached: memory function: cache function operation result
function cached(fn) { let cache = (null); return function cachedFn(str) { let hit = cache[str]; return hit || (cache[str] = fn(str)) } }
16. camelize: name of horizontal line turning into camel
let camelizeRE = /-(\w)/g; function camelize(str) { return (camelizeRE, function(_, c) { return c ? () : ''; }) } //ab-cd-ef ==> abCdEf //Use memory functionlet _camelize = cached(camelize)
17. Hyphenate: Camel naming to horizontal line naming: Split strings, use - to connect, and convert to lowercase
let hyphenateRE = /\B([A-Z])/g; function hyphenate(str){ return (hyphenateRE, '-$1').toLowerCase() } //abCd ==> ab-cd //Use memory functionlet _hyphenate = cached(hyphenate);
18. capitalize: capitalize first position of string
function capitalize(str){ return (0).toUpperCase() + (1) } // abc ==> Abc //Use memory functionlet _capitalize = cached(capitalize)
19. extend: mix attributes into the target object
function extend(to, _from) { for(let key in _from) { to[key] = _from[key]; } return to }
20.: Copy object attributes, shallow copy
= || function(){ if( == 0) throw new TypeError('Cannot convert undefined or null to object'); let target = arguments[0], args = (arguments, 1), key (function(item){ for(key in item){ (key) && ( target[key] = item[key] ) } }) return target }
Use a shallow cloning object:
let clone = ({}, target)
Simple deep cloning can use() and(). These two APIs parse json data, so they can only parse primitive types, arrays and objects except symbol.
let clone = ( (target) )
21. clone: clone data, can be cloned deeply
Here are the cloning rules for primitive types, time, regularity, error, array, object, and others can be supplemented by themselves.
function clone(value, deep){ if(isPrimitive(value)){ return value } if (isArrayLike(value)) { //It is a class array value = (value) return (item => deep ? clone(item, deep) : item) }else if(isPlainObject(value)){ //It's an object let target = {}, key; for (key in value) { (key) && ( target[key] = deep ? clone(value[key], deep) : value[key] ) } } let type = getRawType(value) switch(type){ case 'Date': case 'RegExp': case 'Error': value = new window[type](value); break; } return value }
22. Identify various browsers and platforms
//The running environment is the browserlet inBrowser = typeof window !== 'undefined'; //The operation environment is WeChatlet inWeex = typeof WXEnvironment !== 'undefined' && !!; let weexPlatform = inWeex && (); //Browser UA judgmentlet UA = inBrowser && (); let isIE = UA && /msie|trident/.test(UA); let isIE9 = UA && ('msie 9.0') > 0; let isEdge = UA && ('edge/') > 0; let isAndroid = (UA && ('android') > 0) || (weexPlatform === 'android'); let isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios'); let isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
23. getExplorerInfo: Get browser information
function getExplorerInfo() { let t = (); return 0 <= ("msie") ? { //ie < 11 type: "IE", version: Number((/msie ([\d]+)/)[1]) } : !!(/trident\/.+?rv:(([\d.]+))/) ? { // ie 11 type: "IE", version: 11 } : 0 <= ("edge") ? { type: "Edge", version: Number((/edge\/([\d]+)/)[1]) } : 0 <= ("firefox") ? { type: "Firefox", version: Number((/firefox\/([\d]+)/)[1]) } : 0 <= ("chrome") ? { type: "Chrome", version: Number((/chrome\/([\d]+)/)[1]) } : 0 <= ("opera") ? { type: "Opera", version: Number((/opera.([\d]+)/)[1]) } : 0 <= ("Safari") ? { type: "Safari", version: Number((/version\/([\d]+)/)[1]) } : { type: t, version: -1 } }
24. isPCBroswer: Detect whether it is PC browser mode
function isPCBroswer() { let e = () , t = "ipad" == (/ipad/i) , i = "iphone" == (/iphone/i) , r = "midp" == (/midp/i) , n = "rv:1.2.3.4" == (/rv:1.2.3.4/i) , a = "ucweb" == (/ucweb/i) , o = "android" == (/android/i) , s = "windows ce" == (/windows ce/i) , l = "windows mobile" == (/windows mobile/i); return !(t || i || r || n || a || o || s || l) }
25. Unique: Deduplication of the array, return a new array
function unique(arr){ if(!isArrayLink(arr)){ //Not a class array object return arr } let result = [] let objarr = [] let obj = (null) (item => { if(isStatic(item)){// is the original data except symbol let key = item + '_' + getRawType(item); if(!obj[key]){ obj[key] = true (item) } }else{//Reference type and symbol if(!(item)){ (item) (item) } } }) return resulte }
26. Set simple implementation
= || (function () { function Set(arr) { = arr ? unique(arr) : []; = ; // Array size } = { add: function (value) { // Add an element, if the element already exists, skip it and return to the Set structure itself. if (!(value)) { (value); ++; } return this; }, clear: function () { //Clear all members, no return value. = [] = 0 }, delete: function (value) { //Delete a certain value and return a boolean value to indicate whether the deletion is successful. return ((v, i) => { if(v === value){ (i,1) return true } return false }) }, has: function (value) { //Returns a boolean value indicating whether the value is a member of Set. return (v => v === value) }, values: function () { return }, } return Set; }());
27. repeat: generate a duplicate string consisting of n strs, which can be modified to fill into an array, etc.
function repeat(str, n) { let res = ''; while(n) { if(n % 2 === 1) { res += str; } if(n > 1) { str += str; } n >>= 1; } return res }; //repeat('123',3) ==> 123123123
28. dateFormater: format time
function dateFormater(formater, t){ let date = t ? new Date(t) : new Date(), Y = () + '', M = () + 1, D = (), H = (), m = (), s = (); return (/YYYY|yyyy/g,Y) .replace(/YY|yy/g,(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) } // dateFormater('YYYY-MM-DD HH:mm', t) ==> 2019-06-26 18:30 // dateFormater('YYYYMMDDHHmm', t) ==> 201906261830
29. dateStrForma: converts the specified string from one time format to another
From format should correspond to the position of str
function dateStrForma(str, from, to){ //'20190626' 'YYYMMDD' 'YYYYYYYYYYYMMDD' str += '' let Y = '' if(~(Y = ('YYYY'))){ Y = (Y, 4) to = (/YYYY|yyyy/g,Y) }else if(~(Y = ('YY'))){ Y = (Y, 2) to = (/YY|yy/g,Y) } let k,i ['M','D','H','h','m','s'].forEach(s =>{ i = (s+s) k = ~i ? (i, 2) : '' to = (s+s, k) }) return to } // dateStrForma('20190626', 'YYYMMDD', 'YYYYYYYYYYYYMMDD') ==> June 26, 2019// dateStrForma('121220190626', '----YYYYMMDD', 'YYYYYYYYYYYYYYMMDD') ==> June 26, 2019// dateStrForma('June 26, 2019', 'YYYY MM month DD day', 'YYY MMDD') ==> 20190626 // Generally, you can also use regularity to implement it//'June 26, 2019'.replace(/(\d{4}) year (\d{2}) month (\d{2}) day/, '$1-$2-$3') ==> 2019-06-26
30. getPropByPath: Obj[0].count'
function getPropByPath(obj, path, strict) { let tempObj = obj; path = (/\[(\w+)\]/g, '.$1'); //Convert [0] to .0 path = (/^\./, ''); //Remove the beginning. let keyArr = ('.'); //According to. Cut let i = 0; for (let len = ; i < len - 1; ++i) { if (!tempObj && !strict) break; let key = keyArr[i]; if (key in tempObj) { tempObj = tempObj[key]; } else { if (strict) {//Strict mode is enabled, no corresponding key value is found, an error is thrown throw new Error('please transfer a valid prop path to form item!'); } break; } } return { o: tempObj, //Raw data k: keyArr[i], //key value v: tempObj ? tempObj[keyArr[i]] : null // The value corresponding to the key value }; };
31. GetUrlParam: Get Url parameters and return an object
function GetUrlParam(){ let url = (); let arrObj = ("?"); let params = (null) if ( > 1){ arrObj = arrObj[1].split("&"); (item=>{ item = ("="); params[item[0]] = item[1] }) } return params; } // ?a=1&b=2&c=3 ==> {a: "1", b: "2", c: "3"}
32. DownloadFile: base64 data export file, file download
function downloadFile(filename, data){ let DownloadLink = ('a'); if ( DownloadLink ){ (DownloadLink); = 'display: none'; = filename; = data; if ( ){ let DownloadEvt = ('MouseEvents'); ('click', true, false); (DownloadEvt); } else if ( ) ('onclick'); else if (typeof == 'function' ) (); (DownloadLink); } }
33. toFullScreen: Full Screen
function toFullScreen(){ let elem = ; ? () : ? () : ? () : ? () : alert("The browser does not support full screen"); }
34. exitFullscreen: Exit full screen
function exitFullscreen(){ let elem = ; ? () : ? () : ? () : ? () : ? () : alert("Switching failed, you can try Esc to exit"); }
35. requestAnimationFrame: window animation
= || || || || || function (callback) { //In order to make the effect of setTimteout as close as possible to 60 frames per second (callback, 1000 / 60); }; = || || || || || function (id) { //In order to make the effect of setTimteout as close as possible to 60 frames per second (id); }
36. _isNaN: Check whether the data is a non-numeric value
The native isNaN will convert the parameters into a number (valueof), while null, true, false and arrays with length less than or equal to 1 (elements are non-NaN data) will be converted into numbers, which is not what I want. Symbol type data does not have a valueof interface, so isNaN will throw an error. This is placed behind to avoid errors.
function _isNaN(v){ return !(typeof v === 'string' || typeof v === 'number') || isNaN(v) }
37. max: Find the maximum value in non-NaN data in the array
function max(arr){ arr = (item => !_isNaN(item)) return ? (null, arr) : undefined } //max([1, 2, '11', null, 'fdf', []]) ==> 11
38.min: Find the minimum value in non-NaN data in the array
function min(arr){ arr = (item => !_isNaN(item)) return ? (null, arr) : undefined } //min([1, 2, '11', null, 'fdf', []]) ==> 1
39. random: Return a random number between lower-upper
Lower and upper are both positive and negative and large, but must be non-NaN data.
function random(lower, upper){ lower = +lower || 0 upper = +upper || 0 return () * (upper - lower) + lower; } //random(0, 0.5) ==> 0.3567039135734613 //random(2, 1) ===> 1.6718418553475423 //random(-2, -1) ==> -1.4474325452361945
40.: Return an array composed of its own enumerable properties of a given object.
= || function keys(object) { if(object === null || object === undefined){ throw new TypeError('Cannot convert undefined or null to object'); } let result = [] if(isArrayLike(object) || isPlainObject(object)){ for (let key in object) { (key) && ( (key) ) } } return result }
41.: Return an array of all enumerable attribute values of a given object itself
= || function values(object) { if(object === null || object === undefined){ throw new TypeError('Cannot convert undefined or null to object'); } let result = [] if(isArrayLike(object) || isPlainObject(object)){ for (let key in object) { (key) && ( (object[key]) ) } } return result }
42.: Use the value value to fill the array, start from the start position, end to the end position (but does not include the end position), and return to the original array
= || function fill(value, start, end) { let ctx = this let length = ; start = parseInt(start) if(isNaN(start)){ start = 0 }else if (start < 0) { start = -start > length ? 0 : (length + start); } end = parseInt(end) if(isNaN(end) || end > length){ end = length }else if (end < 0) { end += length; } while (start < end) { ctx[start++] = value; } return ctx; } //Array(3).fill(2) ===> [2, 2, 2]
43.: Used to determine whether an array contains a specified value. If it returns true, otherwise false, you can specify the location where the query starts.
= || function includes(value, start){ let ctx = this let length = ; start = parseInt(start) if(isNaN(start)){ start = 0 }else if (start < 0) { start = -start > length ? 0 : (length + start); } let index = (value) return index >= start; }
44.: Return the value of the first element in the array that passes the test (judged in function fn)
= || function find(fn, ctx){ fn = (ctx) let result; ((value, index, arr), thisValue) => { return fn(value, index, arr) ? (result = value, true) : false }) return result }
45.: Return the subscript of the first element in the array that passes the test (judged in function fn)
= || function findIndex(fn, ctx){ fn = (ctx) let result; ((value, index, arr), thisValue) => { return fn(value, index, arr) ? (result = index, true) : false }) return result }
46.: Use for performance analysis
= function(){ setTimeout(function(){ let t = ('DNS query time :' + ( - ).toFixed(0)) ('TCP link time :' + ( - ).toFixed(0)) ('Request request time :' + ( - ).toFixed(0)) ('Time to parse the dom tree:' + ( - ).toFixed(0)) ('White Screen Time:' + ( - ).toFixed(0)) ('domready time :' + ( - ).toFixed(0)) ('onload time:' + ( - ).toFixed(0)) if(t = ){ ('js memory usage ratio:' + ( / * 100).toFixed(2) + '%') } }) }
47. Disable certain keyboard events
('keydown', function(event){ return !( 112 == || //F1 123 == || //F12 && 82 == || //ctrl + R && 78 == || //ctrl + N && 121 == || //shift + F10 && 115 == || //alt + F4 "A" == && //shift + Click on the a tag ) || ( = false) });
48. Right click, select, copy prohibited
['contextmenu', 'selectstart', 'copy'].forEach(function(ev){ (ev, function(event){ return = false }) });
Github address:/hfhan/tools
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.