封裝了些經常使用的js方法

//*******************************************************************************************//
//       _                           _        _
//      | |                         | |      (_)
//  ____| |__    __ _  _ __    __ _ | |  ___  _
// |_  /| '_ \  / _` || '_ \  / _` || | / _ \| |
//  / / | | | || (_| || | | || (_| || ||  __/| |
// /___||_| |_| \__,_||_| |_| \__, ||_| \___||_|
//                             __/ |
//                            |___/
//*******************************************************************************************//
export const method={
    compress(file){
        return new Promise((resolve)=>{
            if (typeof (FileReader) === 'undefined') {
                throw new Error("當前瀏覽器內核不支持base64圖標壓縮");
            } else {
                try {
                    const reader = new FileReader();
                    reader.onload = e => {
                        const image = new Image();
                        image.src = e.target.result;
                        image.onload =function () {
                            resolve(createCanvas(this));
                        };
                    };
                    reader.readAsDataURL(file);
                } catch(e) {
                    throw new Error("壓縮失敗!");
                }
            }
        });
        function createCanvas(_this) {
            const square = 600;
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            let imageWidth;
            let imageHeight;
            let offsetX = 0;
            let offsetY = 0;
            if (_this.width > _this.height) {
                imageWidth = Math.round(square * _this.width / _this.height);
                imageHeight = square;
            } else {
                imageHeight = Math.round(square * _this.height / _this.width);
                imageWidth = square;
            }
            canvas.width = imageWidth;
            canvas.height = imageHeight;
            context.clearRect(0, 0, imageWidth, imageHeight);
            context.drawImage(_this, offsetX, offsetY, imageWidth, imageHeight);
            return canvas.toDataURL('image/jpeg');
        }
    },
    escapeHTML(t){
        return t.replace(/&/g, "&")
            .replace(/</g, "<")
            .replace(/>/g, ">")
            .replace(/ /g, " ")
            .replace(/"/g, """)
            .replace(/'/g, "'")
    },
    //生成base64格式
    isBase64(element,fn){
        const reader = new FileReader();
        reader.onload = e => {
            fn&&fn(e.target.result);
        };
        reader.onerror = e => {
            fn&&fn();
        };
        reader.readAsDataURL(element);
        return !1;
    },
    setCookie(c_name,value,expiredays){
        const exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=`${c_name}=${value};domain=.paic.com.cn;`/*+exdate.toGMTString()*/
    },
    getCookie(a){
        const b = document.cookie.match(new RegExp(`(^| )${a}=([^;]*)(;|$)`));
        return null !== b ? unescape(b[2]) : null
    },
    deleteCookie(a){
        const b = this.getCookie(a);
        null !== b && this.setCookie(a, "", -1)
    },
    isURL(t){
        return /^(((http[s]?:\/\/)|(ftp:\/\/))?([\w-]+\.)+(com|edu|gov|int|mil|net|org|biz|info|pro|name|museum|coop|aero|xxx|idv|al|dz|af|ar|ae|aw|om|az|eg|et|ie|ee|ad|ao|ai|ag|at|au|mo|bb|pg|bs|pk|py|ps|bh|pa|br|by|bm|bg|mp|bj|be|is|pr|ba|pl|bo|bz|bw|bt|bf|bi|bv|kp|gq|dk|de|tl|tp|tg|dm|do|ru|ec|er|fr|fo|pf|gf|tf|va|ph|fj|fi|cv|fk|gm|cg|cd|co|cr|gg|gd|gl|ge|cu|gp|gu|gy|kz|ht|kr|nl|an|hm|hn|ki|dj|kg|gn|gw|ca|gh|ga|kh|cz|zw|cm|qa|ky|km|ci|kw|cc|hr|ke|ck|lv|ls|la|lb|lt|lr|ly|li|re|lu|rw|ro|mg|im|mv|mt|mw|my|ml|mk|mh|mq|yt|mu|mr|us|um|as|vi|mn|ms|bd|pe|fm|mm|md|ma|mc|mz|mx|nr|np|ni|ne|ng|nu|no|nf|na|za|zq|aq|gs|eu|pw|pn|pt|jp|se|ch|sv|ws|yu|sl|sn|cy|sc|sa|cx|st|sh|kn|lc|sm|pm|vc|lk|sk|si|sj|sz|sd|sr|sb|so|tj|tw|th|tz|to|tc|tt|tn|tv|tr|tm|tk|wf|vu|gt|ve|bn|ug|ua|uy|uz|es|eh|gr|hk|sg|nc|nz|hu|sy|jm|am|ac|ye|iq|ir|il|it|in|id|uk|vg|io|jo|vn|zm|je|td|gi|cl|cf|cn)(:\d+)?(\/[^\s]*)?)$/.test(t)
    },
    isImage(type){
        return /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i.test(type);
    },
    randomRange(start, end){
        return Math.floor(Math.random() * (end - start + 1)) + start;
    },
    countDown(e){
        const t = (new Date(e).getTime() - (new Date).getTime()) / 1e3;
        const n = parseInt(t / 3600 / 7.5);
        const a = parseInt(t / 60 / 60 % 7.5);
        const r = parseInt(t / 60 % 60);
        const o = parseInt(t % 60);
        const i = a < 10 ? `0${a}` : a;
        const l = r < 10 ? `0${r}` : r;
        const s = o < 10 ? `0${o}` : o;
        return n > 0 && `${n}天${i}小時${l}分鐘${s}秒` || a > 0 && `${i}小時${l}分鐘${s}秒` || r > 0 && `${l}分鐘${s}秒` || o > 0 && `${s}秒`
    },
    CheckDateTime(str){
        const reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
        const r = str.match(reg);
        if(r===null){return;}
        r[2]=r[2]-1;
        const d= new Date(r[1], r[2],r[3], r[4],r[5], r[6]);
        if(d.getFullYear()===r[1]&&d.getFullYear()!==r[1]&&d.getMonth()!==r[2]&&d.getDate()!==r[3]&&d.getHours()!==r[4]&&d.getMinutes()!==r[5]&&d.getSeconds()!==r[6])return !0;
    },
    circleFunction :(e, t) =>{
        return t.map(t => e[t] = e[t].bind(e))
    },
    formatTime(e,d = 7.5){
        const t = parseInt(e);
        const n = parseInt(t / 3600/d);
        const a = parseInt(t / 3600 - d * n);
        const r = parseInt(t / 60 - 60 * a - d * n * 60);
        const o = parseInt(t - 60 * r - 3600 * a - d * n * 3600);
        const i = a < 10 ? `0${a}` : a;
        const l = r < 10 ? `0${r}` : r;
        const s = o < 10 ? `0${o}` : o;
        return n > 0 && `${n}天${i}小時${l}分鐘${s}秒` || a > 0 && `${i}小時${l}分鐘${s}秒` || r > 0 && `${l}分鐘${s}秒` || o > 0 && `${s}秒`
    },
    getObjKeys(obj){
        if (Object.keys) return Object.keys(obj);
        const t = [];
        for (const n in obj) Object.prototype.hasOwnProperty.call(obj, n) && t.push(n);
        return t
    },
    getDom(element){
        const chartName = element.charAt(0);
        switch (chartName){
            case '.':return document.querySelector(`${element}`);
            case '#':return document.getElementsByName(`${element}`);
            default:return document.getElementsByTagName(`${element}`);
        }
    },
    addLocalStorage(...args){
        if(args.length !== 2)throw new Error('格式不對');
        if(!window.localStorage)throw new Error('不支持此方法');
        (this.isObject(args[1])||this.isArray(args[1]))?localStorage.setItem(args[0],JSON.stringify(args[1])):localStorage.setItem(args[0],args[1]);
    },
    addManyLocal(obj){
        if(!window.localStorage)throw new Error('不支持此方法');
        this.getObjKeys(obj).forEach(k=>{
            return this.addLocalStorage(k,obj[k])
        })
    },
    getLocalStorage(key){
        if (!window.localStorage)throw new Error("不支持此方法");
        const t = localStorage.getItem(key);
        try{
            return JSON.parse(t)
        }catch (e){
            return t;
        }
    },
    removeLocalStorage(key){
        if (!window.localStorage) throw new Error("不支持此方法");
        localStorage.removeItem(key)
    },
    clearLocalStorage(){
        if (!window.localStorage) throw new Error("不支持此方法");
        localStorage.clear()
    },
    isString(str){
        return typeof str ==='string';
    },
    getStrLength(str){
        let len = 0;
        str.split('').forEach(item=>{
            item.charCodeAt(0) < 256?len++:len+=2
        });
        return len
    },
    isArray(e){
        return "[object Array]" === Object.prototype.toString.call(e)
    },
    arrayRepetition(array=[]){
        return [...new Set(array)];
    },
    arrayUnico(array1,array2){
        return new Set([...array1,...array2]);
    },
    arrayIntersect(array1,array2){
        return new Set(array1.filter(item=>array2.has(item)));
    },
    arrayDifference(array1,array2){
        return new Set(array1.filter(item=>!array2.has(item)));
    },
    arrayHasObj(arr, id){
        return arr.some(item=>item.id === id);
    },
    unEmptyArray(arr){
        return arr&&arr.length>0;
    },
    isObject(e) {
        return "[object Object]" === Object.prototype.toString.call(e)
    },
    isEmptyObj(obj){
        for (const t in obj) return !1;
        return !0
    },
    isEmptyObjContent(obj){
        return !Object.keys(obj).some(item=>obj[item]&&obj[item].length>0)
    },
    cloneObj(obj){
        let str = null;
        let newObj = {};
        if(typeof obj !=='object'){
            return;
        }else if(window.JSON){
            str = JSON.stringify(obj);
            newObj = JSON.parse(str);
        }else{
            for(let a in obj){
                newObj[a] = this.cloneObj(obj[a]);
            }
        }
        return newObj;
    },
    removeHtml(str){
        return str.replace(/<[^>]+>/g,"")
    },
    removeStyle(str){
        return str.replace(/style="[^"]*"/g,"")
    },
    removeSpace(str){
        return str.replace(/^( |\s)+|( |\s)+$/g,'')
    },
    reCn(str){
        return str.replace(/([\u4E00-\u9FA5]|[\uFE30-\uFFA0])+/gi,'-');
    },
    addEvent(e, t, n) {
        e.addEventListener ? e.addEventListener(t, n, !1) : e.attachEvent(`on${t}`, n)
    },
    removeEvent(e, t, n) {
        e.removeEventListener ? e.removeEventListener(t, n, !1) : e.detachEvent(`on${t}`, n)
    },
    //動畫
    zhangleiAnimate(dom, m, t, d){
        dom.style.cssText =  `-webkit-animation:${m} ${t}s ease-in-out 1 ${d}s alternate forwards`;
        dom.style.cssText =  `-moz-animation:${m} ${t}s ease-in-out 1 ${d}s alternate forwards`;
        dom.style.cssText =  `-o-animation:${m} ${t}s ease-in-out 1 ${d}s alternate forwards`;
        dom.style.cssText =  `animation:${m} ${t}s ease-in-out 1 ${d}s alternate forwards`;
    },
    jsonToStr(json){
        if (typeof json === 'object') {
            return JSON && JSON.stringify(json);
        }
    },
    strToJson(str){
        if ("string" === typeof str) return JSON && JSON.parse(str)
    },
    ucase(string){
        return string.charAt(0).toUpperCase() + string.slice(1);
    },
    compareTime(stime, etime){
        const t1 = new Date(stime);
        const t2 = new Date(etime);
        return Date.parse(t2) - Date.parse(t1);
    },
    stopBubble(e){
        const t = e || window.event;
        return t.stopPropagation ? t.stopPropagation() : t.cancelBubble = !0
    },
    upperCase(str){
        return str&&str.toUpperCase();
    },
    isCurrentDay(time){
        const y = time.getFullYear();
        const month = time.getMonth()+1;
        const day = time.getDate();
        const m = month < 10 ? `0${month}` : month;
        const d = day < 10 ? `0${day}` : day;
        return `${y}-${m}-${d}`
    },
    isCurrentDayOne(time){
        const y = time.getFullYear();
        const month = time.getMonth()+1;
        //const day = time.getDate();
        const m = month < 10 ? `0${month}` : month;
        //const d = day < 10 ? `0${day}` : day;
        return `${y}-${m}-01`
    },
    isCurrentTime(time){
        const y = time.getFullYear();
        const month = time.getMonth()+1;
        const hour = time.getHours();
        const min = time.getMinutes();
        const sec = time.getSeconds();
        const day = time.getDate();
        const m = month < 10 ? `0${month}` : month;
        const h = hour < 10 ? `0${hour}` : hour;
        const mins = min < 10 ? `0${min}` : min;
        const s = sec < 10 ? `0${sec}` : sec;
        const d = day < 10 ? `0${day}` : day;
        return `${y}-${m}-${d} ${h}:${mins}:${s}`
    },
    maxInArray(arr){
        return Math.max.apply(Math,arr);
    },
    minInArray(arr){
        return Math.min.apply(Math,arr)
    },
    sameArray(e){
        const n = e.sort();
        return n.map((m,i,a)=>a[i] === a[i+1]&&a[i])
    }
};
相關文章
相關標籤/搜索