JavaScript Develops Common Tool Functions

Keywords: Front-end Windows JSON Android IE

1. isStatic: Detecting whether the data is original except symbol s

function isStatic(value) {
    return(
        typeof value === 'string' ||
        typeof value === 'number' ||
        typeof value === 'boolean' ||
        typeof value === 'undefined' ||
        value === null
    )
}

2. isPrimitive: Detecting whether the data is the original data

function isPrimitive(value) {
    return isStatic(value) || typeof value === 'symbol'
}

3. isObject: Data that determines whether the data refers to a type (e.g. 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 Number, String, Object, Array, etc.

function getRawType(value) {
    return Object.prototype.toString.call(value).slice(8, -1)
}
//getoRawType([]) ==> Array

6. isPlainObject: Determine whether the data is Object-type data

function isPlainObject(obj) {
    return Object.prototype.toString.call(obj) === '[object Object]'
}

7. isArray: Data that determines whether or not the data is of array type

function isArray(arr) {
    return Object.prototype.toString.call(arr) === '[object Array]'
}

Mount isArray on Array

Array.isArray = Array.isArray || isArray;

8. isRegExp: Determine whether the data is a regular object

function isRegExp(value) {
    return Object.prototype.toString.call(value) === '[object RegExp]'
}

9. isDate: Determining whether data is a time object

function isDate(value) {
    return Object.prototype.toString.call(value) === '[object Date]'
}

10. isNative: Determine whether value is a browser built-in function

The body code block after the built-in Function toString is [native code], while the non-built Function is the relevant code, so the non-built Function can be copied.

function isNative(value) {
    return typeof value === 'function' && /native code/.test(value.toString())
}

11. isFunction: Check whether value is a function

function isFunction(value) {
    return Object.prototype.toString.call(value) === '[object Function]'
}

isLength: Check whether value is a 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 value is an array of classes

If a value is considered an array of classes, then it is not a function, and value.length 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(value.length) && !isFunction(value);
}

isEmpty: Check whether value is empty

If it is null, it returns true directly; if it is an array of classes, it judges the length of data; if it is an Object object, it judges whether it has attributes; if it is other data, it returns false directly (or it can be changed to return true).

function isEmpty(value) {
    if (value == null) {
        return true;
    }
    if (isArrayLike(value)) {
        return !value.length;
    }else if(isPlainObject(value)){
          for (let key in value) {
            if (hasOwnProperty.call(value, key)) {
              return false;
            }
        }
        return true;
    }
    return false;
}

15. cached: Memory Function: Operational Results of cached Function

function cached(fn) {
    let cache = Object.create(null);
    return function cachedFn(str) {
        let hit = cache[str];
        return hit || (cache[str] = fn(str))
    }
}

16. camelize: Naming of Horizontal Hump

let camelizeRE = /-(\w)/g;
function camelize(str) {
    return str.replace(camelizeRE, function(_, c) {
        return c ? c.toUpperCase() : '';
    })
}
//ab-cd-ef ==> abCdEf
//Using memory function
let _camelize = cached(camelize)

17. hyphenate: Hump Naming Turn Horizontal Naming: Split Strings, Use - Connect, and Convert to lowercase

let hyphenateRE = /\B([A-Z])/g;
function hyphenate(str){
    return str.replace(hyphenateRE, '-$1').toLowerCase()
}
//abCd ==> ab-cd
//Using memory function
let _hyphenate = cached(hyphenate);

18. capitalize: the first capitalization of a string

function capitalize(str){
    return str.charAt(0).toUpperCase() + str.slice(1)
}
// abc ==> Abc
//Using memory function
let _capitalize = cached(capitalize)

19. extend: Mixing attributes into the target object

function extend(to, _from) {
    for(let key in _from) {
        to[key] = _from[key];
    }
    return to
}

Object.assign: Object property replication, shallow copy

Object.assign = Object.assign || function(){
    if(arguments.length == 0) throw new TypeError('Cannot convert undefined or null to object');
    
    let target = arguments[0],
        args = Array.prototype.slice.call(arguments, 1),
        key
    args.forEach(function(item){
        for(key in item){
            item.hasOwnProperty(key) && ( target[key] = item[key] )
        }
    })
    return target
}

An object can be shallowly cloned using Object.assign:

let clone = Object.assign({}, target)

Simple deep cloning can use JSON.parse() and JSON.stringify(), which are APIs for parsing json data, so only primitive types and arrays and objects except symbol s can be parsed.

let clone = JSON.parse( JSON.stringify(target) )

clone: clone data, deep cloning

Here are the original types, time, regularity, errors, arrays, cloning rules for objects, others can be supplemented by themselves.

function clone(value, deep){
    if(isPrimitive(value)){
        return value
    }
    
    if (isArrayLike(value)) { //Is an array of classes
        value = Array.prototype.slice.call(value)
        return value.map(item => deep ? clone(item, deep) : item)
       }else if(isPlainObject(value)){ //Is the object
           let target = {}, key;
          for (key in value) {
            value.hasOwnProperty(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 browsers and platforms

//Running environment is browser
let inBrowser = typeof window !== 'undefined';
//Operating environment is Wechat
let inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;
let weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();
//Browser UA Judgment
let UA = inBrowser && window.navigator.userAgent.toLowerCase();
let isIE = UA && /msie|trident/.test(UA);
let isIE9 = UA && UA.indexOf('msie 9.0') > 0;
let isEdge = UA && UA.indexOf('edge/') > 0;
let isAndroid = (UA && UA.indexOf('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: Getting Browser Information

function getExplorerInfo() {
    let t = navigator.userAgent.toLowerCase();
    return 0 <= t.indexOf("msie") ? { //ie < 11
        type: "IE",
        version: Number(t.match(/msie ([\d]+)/)[1])
    } : !!t.match(/trident\/.+?rv:(([\d.]+))/) ? { // ie 11
        type: "IE",
        version: 11
    } : 0 <= t.indexOf("edge") ? {
        type: "Edge",
        version: Number(t.match(/edge\/([\d]+)/)[1])
    } : 0 <= t.indexOf("firefox") ? {
        type: "Firefox",
        version: Number(t.match(/firefox\/([\d]+)/)[1])
    } : 0 <= t.indexOf("chrome") ? {
        type: "Chrome",
        version: Number(t.match(/chrome\/([\d]+)/)[1])
    } : 0 <= t.indexOf("opera") ? {
        type: "Opera",
        version: Number(t.match(/opera.([\d]+)/)[1])
    } : 0 <= t.indexOf("Safari") ? {
        type: "Safari",
        version: Number(t.match(/version\/([\d]+)/)[1])
    } : {
        type: t,
        version: -1
    }
}

IsPC Broswer: Check for PC-side browser mode

function isPCBroswer() {
    let e = navigator.userAgent.toLowerCase()
        , t = "ipad" == e.match(/ipad/i)
        , i = "iphone" == e.match(/iphone/i)
        , r = "midp" == e.match(/midp/i)
        , n = "rv:1.2.3.4" == e.match(/rv:1.2.3.4/i)
        , a = "ucweb" == e.match(/ucweb/i)
        , o = "android" == e.match(/android/i)
        , s = "windows ce" == e.match(/windows ce/i)
        , l = "windows mobile" == e.match(/windows mobile/i);
    return !(t || i || r || n || a || o || s || l)
}

25. unique: array de-duplication, returning a new array

function unique(arr){
    if(!isArrayLink(arr)){ //Not a class array object
        return arr
    }
    let result = []
    let objarr = []
    let obj = Object.create(null)
    
    arr.forEach(item => {
        if(isStatic(item)){//It's raw data except symbol s.
            let key = item + '_' + getRawType(item);
            if(!obj[key]){
                obj[key] = true
                result.push(item)
            }
        }else{//Reference type and symbol
            if(!objarr.includes(item)){
                objarr.push(item)
                result.push(item)
            }
        }
    })
    
    return resulte
}

26. Set Simple Implementation

window.Set = window.Set || (function () {
    function Set(arr) {
        this.items = arr ? unique(arr) : [];
        this.size = this.items.length; // The size of Array
    }
    Set.prototype = {
        add: function (value) {
            // Add elements, skip if they already exist, and return to the Set structure itself.
            if (!this.has(value)) {
                this.items.push(value);
                this.size++;
            }
            return this;
        },
        clear: function () {
            //Clear all members, no return value.
            this.items = []
            this.size = 0
        },
        delete: function (value) {
            //Delete a value and return a Boolean value to indicate whether the deletion was successful.
            return this.items.some((v, i) => {
                if(v === value){
                    this.items.splice(i,1)
                    return true
                }
                return false
            })
        },
        has: function (value) {
            //Returns a Boolean value indicating whether the value is a member of Set.
            return this.items.some(v => v === value)
        },
        values: function () {
            return this.items
        },
    }

    return Set;
}());

27. repeat: Generate a duplicate str ing consisting of n STRs that can be modified to fill in 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

dateFormater: Format time

function dateFormater(formater, t){
    let date = t ? new Date(t) : new Date(),
        Y = date.getFullYear() + '',
        M = date.getMonth() + 1,
        D = date.getDate(),
        H = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds();
    return formater.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)
}
// dateFormater('YYYY-MM-DD HH:mm', t) ==> 2019-06-26 18:30
// dateFormater('YYYYMMDDHHmm', t) ==> 201906261830

dateStrForma: Converting a specified string from one time format to another

from format should correspond to str location

function dateStrForma(str, from, to){
    //'2010 90626''YYYYY MM DD''YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
    str += ''
    let Y = ''
    if(~(Y = from.indexOf('YYYY'))){
        Y = str.substr(Y, 4)
        to = to.replace(/YYYY|yyyy/g,Y)
    }else if(~(Y = from.indexOf('YY'))){
        Y = str.substr(Y, 2)
        to = to.replace(/YY|yy/g,Y)
    }

    let k,i
    ['M','D','H','h','m','s'].forEach(s =>{
        i = from.indexOf(s+s)
        k = ~i ? str.substr(i, 2) : ''
        to = to.replace(s+s, k)
    })
    return to
}
// DateStrForma ('20190626','YYYYYMMDD','YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYMMMonth DD Day') ==> June 26, 2019
// DateStrForma ('121220190626','- - YYYYYMMDD','YYYYYYYYYYYMMDD') => June 26, 2019
// DateStrForma ('June 26, 2019','YYYYYYYYYYMMDD','YYYYYMMDD') => 20190626

// Ordinary can also be implemented using regularization.
//'June 26, 2019'. replace (/( D {4}) year ( d{2}) month ( d{2}) day /,'$1 - $2 - $3') => 2019-06-26

30. getPropByPath: Get the object property according to the string path:'obj[0].count'

function getPropByPath(obj, path, strict) {
      let tempObj = obj;
      path = path.replace(/\[(\w+)\]/g, '.$1'); //Convert [0] to.0
      path = path.replace(/^\./, ''); //Remove the beginning.

      let keyArr = path.split('.'); //According to. Cutting
      let i = 0;
      for (let len = keyArr.length; i < len - 1; ++i) {
        if (!tempObj && !strict) break;
        let key = keyArr[i];
        if (key in tempObj) {
            tempObj = tempObj[key];
        } else {
            if (strict) {//Open strict mode, no corresponding key value found, throw an error
                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
      };
};

GetUrlParam: Get Url parameters and return an object

function GetUrlParam(){
    let url = document.location.toString();
    let arrObj = url.split("?");
    let params = Object.create(null)
    if (arrObj.length > 1){
        arrObj = arrObj[1].split("&");
        arrObj.forEach(item=>{
            item = item.split("=");
            params[item[0]] = item[1]
        })
    }
    return params;
}
// ?a=1&b=2&c=3 ==> {a: "1", b: "2", c: "3"}

32. Download File: base64 Data Export File, File Download

function downloadFile(filename, data){
    let DownloadLink = document.createElement('a');

    if ( DownloadLink ){
        document.body.appendChild(DownloadLink);
        DownloadLink.style = 'display: none';
        DownloadLink.download = filename;
        DownloadLink.href = data;

        if ( document.createEvent ){
            let DownloadEvt = document.createEvent('MouseEvents');

            DownloadEvt.initEvent('click', true, false);
            DownloadLink.dispatchEvent(DownloadEvt);
        }
        else if ( document.createEventObject )
            DownloadLink.fireEvent('onclick');
        else if (typeof DownloadLink.onclick == 'function' )
            DownloadLink.onclick();

        document.body.removeChild(DownloadLink);
    }
}

33. toFull Screen: Full Screen

function toFullScreen(){
    let elem = document.body;
    elem.webkitRequestFullScreen 
    ? elem.webkitRequestFullScreen()
    : elem.mozRequestFullScreen
    ? elem.mozRequestFullScreen()
    : elem.msRequestFullscreen
    ? elem.msRequestFullscreen()
    : elem.requestFullScreen
    ? elem.requestFullScreen()
    : alert("Browsers do not support full screen");
}

Exit Full screen: Exit Full screen

function exitFullscreen(){
    let elem = parent.document;
    elem.webkitCancelFullScreen 
    ? elem.webkitCancelFullScreen()
    : elem.mozCancelFullScreen
    ? elem.mozCancelFullScreen()
    : elem.cancelFullScreen
    ? elem.cancelFullScreen()
    : elem.msExitFullscreen
    ? elem.msExitFullscreen()
    : elem.exitFullscreen
    ? elem.exitFullscreen()
    : alert("Handover failure,Attemptable Esc Sign out");
}

35. Request Animation Frame: Windows Animation

window.requestAnimationFrame = window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    function (callback) {
        //To make setTimteout as close as possible to 60 frames per second
        window.setTimeout(callback, 1000 / 60);
    };
    
window.cancelAnimationFrame = window.cancelAnimationFrame ||
    Window.webkitCancelAnimationFrame ||
    window.mozCancelAnimationFrame ||
    window.msCancelAnimationFrame ||
    window.oCancelAnimationFrame ||
    function (id) {
        //To make setTimteout as close as possible to 60 frames per second
        window.clearTimeout(id);
    }

36, _isNaN: Check whether the data is non-numeric

Native isNaN converts parameters into values, while null, true, false and arrays less than 1 in length (elements are non-NaN data) are converted into numbers, which is not what I want. Symbol-type data does not have a valueof interface, so isNaN throws errors, which can be avoided by placing them in the back.

function _isNaN(v){
    return !(typeof v === 'string' || typeof v === 'number') || isNaN(v)
}

37, max: Find the maximum value of non-NaN data in an array

function max(arr){
    arr = arr.filter(item => !_isNaN(item))
    return arr.length ? Math.max.apply(null, arr) : undefined
}
//max([1, 2, '11', null, 'fdf', []]) ==> 11

38, min: Find the minimum value of non-NaN data in an array

function min(arr){
    arr = arr.filter(item => !_isNaN(item))
    return arr.length ? Math.min.apply(null, arr) : undefined
}
//min([1, 2, '11', null, 'fdf', []]) ==> 1

39. random: Returns a random number between lower - upper

lower and upper must be non-NaN data, regardless of size or positive.

function random(lower, upper){
    lower = +lower || 0
    upper = +upper || 0
    return Math.random() * (upper - lower) + lower;
}
//random(0, 0.5) ==> 0.3567039135734613
//random(2, 1) ===> 1.6718418553475423
//random(-2, -1) ==> -1.4474325452361945

Object.keys: Returns an array of enumerable attributes of a given object

Object.keys = Object.keys || 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) {
            object.hasOwnProperty(key) && ( result.push(key) )
        }
    }
    return result
}

Object.values: Returns an array of all enumerable attribute values for a given object itself

Object.values = Object.values || 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) {
            object.hasOwnProperty(key) && ( result.push(object[key]) )
        }
    }
    return result
}

42. arr.fill: Fill the array with the value value, starting at the start position and ending at the end position (but excluding the end position), and return to the original array

Array.prototype.fill = Array.prototype.fill || function fill(value, start, end) {
    let ctx = this
    let length = ctx.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. arr. include: Used to determine whether an array contains a specified value. If true is returned, otherwise false, you can specify where to start the query.

Array.prototype.includes = Array.prototype.includes || function includes(value, start){
    let ctx = this
    let length = ctx.length;
    
    start = parseInt(start)
    if(isNaN(start)){
        start = 0
    }else if (start < 0) {
        start = -start > length ? 0 : (length + start);
      }
    
    let index = ctx.indexOf(value)
    
    return index >= start;
}

44. arr.find: Returns the value of the first element in the array that passed the test (judged within function fn)

Array.prototype.find = Array.prototype.find || function find(fn, ctx){
    fn = fn.bind(ctx)
    
    let result;
    this.some((value, index, arr), thisValue) => {
        return fn(value, index, arr) ? (result = value, true) : false
    })
    
    return result
}

45. arr.findIndex: Returns the subscript of the first element in the array that passed the test (judged within function fn)

Array.prototype.findIndex = Array.prototype.findIndex || function findIndex(fn, ctx){
    fn = fn.bind(ctx)
    
    let result;
    this.some((value, index, arr), thisValue) => {
        return fn(value, index, arr) ? (result = index, true) : false
    })
    
    return result
}

46. performance.timing: Performance analysis using performance.timing

window.onload = function(){
    setTimeout(function(){
        let t = performance.timing
        console.log('DNS Query time-consuming:' + (t.domainLookupEnd - t.domainLookupStart).toFixed(0))
        console.log('TCP Link time-consuming:' + (t.connectEnd - t.connectStart).toFixed(0))
        console.log('request Request time-consuming:' + (t.responseEnd - t.responseStart).toFixed(0))
        console.log('analysis dom Trees take time:' + (t.domComplete - t.domInteractive).toFixed(0))
        console.log('White screen time:' + (t.responseStart - t.navigationStart).toFixed(0))
        console.log('domready Time:' + (t.domContentLoadedEventEnd - t.navigationStart).toFixed(0))
        console.log('onload Time:' + (t.loadEventEnd - t.navigationStart).toFixed(0))

        if(t = performance.memory){
            console.log('js Memory usage ratio:' + (t.usedJSHeapSize / t.totalJSHeapSize * 100).toFixed(2) + '%')
        }
    })
}

47. Prohibit certain keyboard events

document.addEventListener('keydown', function(event){
    return !(
        112 == event.keyCode || //F1
        123 == event.keyCode || //F12
        event.ctrlKey && 82 == event.keyCode || //ctrl + R
        event.ctrlKey && 78 == event.keyCode || //ctrl + N
        event.shiftKey && 121 == event.keyCode || //shift + F10
        event.altKey && 115 == event.keyCode || //alt + F4
        "A" == event.srcElement.tagName && event.shiftKey //shift + Click the a tab
    ) || (event.returnValue = false)
});

48. Forbid Right-click, Select, Copy

['contextmenu', 'selectstart', 'copy'].forEach(function(ev){
    document.addEventListener(ev, function(event){
        return event.returnValue = false
    })
});

Code Cloud Address: https://gitee.com/incess/jsgongjuhanshu

Posted by xcmir on Tue, 23 Jul 2019 20:56:19 -0700