Content provider: Jinniu District Wudi Software Development Studio

To follow:Front-end Development common JS functions (part 1)

  1. Unique: Unduplicate the array, returning a new array
function unique(arr){
    if(! isArrayLink(arr)){// Not an array-like object
        return arr
    }
    let result = []
    let objarr = []
    let obj = Object.create(null)
    
    arr.forEach(item= > {
        if(isStatic(item)){// is the original data except symbol
            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
}
Copy the code
  1. Simple implementation of Set
window.Set = window.Set || (function () {
    function Set(arr) {
        this.items = arr ? unique(arr) : [];
        this.size = this.items.length; // Array size
    }
    Set.prototype = {
        add: function (value) {
            // Add the element, skip if the element already exists, and return the Set structure itself.
            if (!this.has(value)) {
                this.items.push(value);
                this.size++;
            }
            return this;
        },
        clear: function () {
            // Clears all members with no return value.
            this.items = []
            this.size = 0
        },
        delete: function (value) {
            // Delete a value, return a Boolean value indicating 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; } ());Copy the code
  1. Repeat: Generates a repeated string consisting of n STR that 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
Copy the code
  1. 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
Copy the code
  1. DateStrForma: Converts the specified string from one time format to another. The form From should correspond to the position of STR
function dateStrForma(str, from, to){
    //'20190626' 'YYYYMMDD' 'YYYYMMDD'
    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', 'YYYYMMDD', 'YYYYMMDD') ==> June 26, 2019
// dateStrForma('121220190626', '----YYYYMMDD', 'YYYYMMDD') ==> June 26, 2019
// dateStrForma(' YYYYMMDD', 'YYYYMMDD') ==> 20190626

// This can also be done using regular
/ / 'on June 26, 2019. The replace ()/(\ d {4}) on (\ d {2})/(\ d {2}),' $1 - $2 - $3) = = > 2019-06-26
Copy the code
  1. GetPropByPath: Get object properties based on 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 initial.

      let keyArr = path.split('. '); // According to.cut
      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) {// Enable strict mode, no corresponding key is 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 values
        v: tempObj ? tempObj[keyArr[i]] : null // The value of the key value
      };
};
Copy the code
  1. GetUrlParam: Gets the Url argument and returns 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"}
Copy the code
  1. DownloadFile: base64 Indicates a data export file that can be downloaded
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); }}Copy the code
  1. ToFullScreen: 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("Browser does not support full screen");
}
Copy the code
  1. ExitFullscreen: Exits the 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("Switchover failed. Try Esc to exit.");
}
Copy the code
  1. RequestAnimationFrame: Window animation
window.requestAnimationFrame = window.requestAnimationFrame ||
	window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    function (callback) {
		// To get setTimteout as close to 60 frames per second as possible
		window.setTimeout(callback, 1000 / 60);
	}
window.cancelAnimationFrame = window.cancelAnimationFrame ||
	window.webkitCancelAnimationFrame ||
    window.mozCancelAnimationFrame ||
    window.msCancelAnimationFrame ||
    window.oCancelAnimationFrame ||
    function (id) {
		// To get setTimteout as close to 60 frames per second as possible
        window.clearTimeout(id);
	}
Copy the code
  1. _isNaN: Checks whether data is a non-numeric value
function _isNaN(v){
    return! (typeof v === 'string' || typeof v === 'number') | |isNaN(v)
}
Copy the code
  1. Max: Finds the maximum value of non-nan data in the 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
Copy the code
  1. Min: Finds the minimum value in the array that is not a NaN
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
Copy the code
  1. Random: Returns a lower-upper direct random number. (Lower, upper must be non-nan data regardless of positive, negative or size)
function random(lower, upper) {
	lower = +lower || 0
	upper = +upper || 0
	return Math.random() * (upper - lower) + lower;
}
/ / the random (0, 0.5) = = > 0.3567039135734613
/ / the random (2, 1) = = = > 1.6718418553475423
/ / the random (2, 1) = = > 1.4474325452361945
Copy the code
  1. Keys: Returns an array of the self-enumerable properties 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;
}
Copy the code
  1. Object.values: Returns an array of all enumerable property 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;
}
Copy the code
  1. Arr.fill: Fills the array with values, starting at start and ending at end (but not end), returning 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]
Copy the code
  1. Arr.includes: Determines whether an array contains a specified value, returns true if so, false otherwise, and specifies the location 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;
}
Copy the code
  1. Returns the value of the first element in the array that passes the test (judged in function fn)
Array.prototype.find = Array.prototype.find || function find(fn, ctx) {
	ctx = ctx || this;
	let result;
	ctx.some((value, index, arr), thisValue) => {
		return fn(value, index, arr) ? (result = value, true) : false
	})
	return result
}
Copy the code
  1. Arr.findindex: Returns the index of the first element in the array that passes the test (judged in function fn)

Array.prototype.findIndex = Array.prototype.findIndex || function findIndex(fn, ctx){
    ctx = ctx || this
    
    let result;
    ctx.some((value, index, arr), thisValue) => {
        return fn(value, index, arr) ? (result = index, true) : false
    })
    
    return result
}
Copy the code
  1. Performance. Timing: Performance. Timing is used to analyze performance
window.onload = function() {
	setTimeout(function() {
		let t = performance.timing;
		console.log('DNS query time: ' + (t.domainLookupEnd - t.domainLookupStart).toFixed(0))
        console.log('TCP connection Time: ' + (t.connectEnd - t.connectStart).toFixed(0))
        console.log('Request Request time:' + (t.responseEnd - t.responseStart).toFixed(0))
        console.log(Dom tree parsing 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) + The '%')}}}Copy the code
  1. Disallow certain keyboard events
document.addEventListener('keydown'.function(event) {
	return! (112 == event.keyCode ||		/ / F1 is prohibited
		123 == event.keyCode ||		/ / F12 is prohibited
		event.ctrlKey && 82 == event.keyCode ||		/ / CTRL + R is prohibited
		event.ctrlKey && 18 == event.keyCode ||		/ / CTRL + N is prohibited
		event.shiftKey && 121 == event.keyCode ||  		/ / shift + F10 is prohibited
		event.altKey && 115 == event.keyCode ||		/ / Alt + F4 is prohibited
		"A" == event.srcElement.tagName && event.shiftKey		// Disable shift+ clicking on the A TAB) | | (event. ReturnValue =false)});Copy the code
  1. Right-click, select, and copy are prohibited
['contextmenu'.'selectstart'.'copy'].forEach(function(ev) {
	document.addEventListener(ev, function(event) {
		return event.returnValue = false; })});Copy the code

Next: front-end development common JS function functions (next)