zoukankan      html  css  js  c++  java
  • 和业务相关的工具函数

    // 获取字符长度
    export function getStringLen (str) {
        let len = 0;
        for (let i = 0; i < str.length; i++) {
            if (str.charCodeAt(i) > 127 || str.charCodeAt(i) == 94) {
                len += 2;
            } else {
                len ++;
            }
        }
        return len;
    }

    【距离今天多久之前的时间段,关键点是把时间都以毫秒换算】

    /**
     * @description 获取距离今天多久之前的时间段
     * @param {Number} unit  单位    0: 天   1: 周   2: 月
     * @param {Number} count 数值
     * @returns {Array} [yyyy-MM-dd, yyyy-MM-dd]
     */
    export function sinceToday(unit, count) {
        const DAY = 60 * 60 * 24 * 1000;
        const endTime = new Date();
        let startTime = null;
    
        endTime.setDate(endTime.getDate() + 1);
        endTime.setHours(0);
        endTime.setMinutes(0);
        endTime.setSeconds(0);
        endTime.setMilliseconds(0);
    
        switch (unit) {
            case 0:     //
                startTime = endTime.getTime() - count * DAY;
    
                break;
            case 1:     //
                startTime = endTime.getTime() - count * DAY * 7;
    
                break;
    
            case 2:     //
                const currentMonth = endTime.getMonth();
                startTime = new Date().setMonth(currentMonth - count);
    
                break;
    
            default:
                startTime = endTime.getTime();
    
                break;
        }
    
        if (unit === 0) {
            // 今天
            if (count === 0) {
                return [number2DateTime( new Date().getTime(), 'yyyy-MM-dd'), number2DateTime( new Date().getTime(), 'yyyy-MM-dd')];
            }
    
            // 昨天
            if (count === 1) {
                return [number2DateTime(startTime - 1, 'yyyy-MM-dd'), number2DateTime(startTime - 1, 'yyyy-MM-dd')];
            }
        }
    
        return [number2DateTime(startTime + DAY - 1, 'yyyy-MM-dd'), number2DateTime(endTime.getTime() - 1, 'yyyy-MM-dd')];
    }

    【深层遍历数据,将深层结构拆成扁平结构,并利用了数据引用类型的特点】

    /**
     * 
     * @param {Array} data              被遍历的数据
     * @param {Function} callback       遍历到某个结点时要执行的回调,三个回调参数为 当前结点、当前结点在父元素中的下标、父元素
     * @param {String} childkey         存储子结点的属性值
     */
    export function traversalTree(data, callback, childkey = 'ChildrenList') {
        const queue = [data];
    
        while (queue.length) {
            const nodes = queue.shift();
    
            for (let i = nodes.length - 1; i >= 0; i--) {
                nodes[i][childkey] && queue.push(nodes[i][childkey]);
                callback(nodes[i], i, nodes);
            }
        }
    }

    【深度复制】

    // 深复制

    export function clone(obj) {
        var copy;
        // Handle the 3 simple types, and null or undefined
        if (null == obj || "object" != typeof obj) return obj;
    
        // Handle Date
        if (obj instanceof Date) {
            copy = new Date();
            copy.setTime(obj.getTime());
            return copy;
        }
    
        // Handle Array
        if (obj instanceof Array) {
            copy = [];
            for (var i = 0, len = obj.length; i < len; i++) {
                copy[i] = clone(obj[i]);
            }
            return copy;
        }
    
        // Handle Object
        if (obj instanceof Object) {
            copy = {};
            for (var attr in obj) {
                if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
            }
            return copy;
        }
    
        throw new Error("Unable to copy obj! Its type isn't supported.");
    }

    【对象比较】

    export function diff(obj1, obj2) { // 对象比较
        var o1 = obj1 instanceof Object;
        var o2 = obj2 instanceof Object;
        if (!o1 || !o2) { /*  判断不是对象  */
            return obj1 === obj2;
        }
    
        if (Object.keys(obj1).length !== Object.keys(obj2).length) {
            return false;
            //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如:数组返回下表:let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
        }
    
        for (var attr in obj1) {
            var t1 = obj1[attr] instanceof Object;
            var t2 = obj2[attr] instanceof Object;
            if (t1 && t2) {
                return diff(obj1[attr], obj2[attr]);
            } else if (!obj1[attr] && !obj2[attr]) {
                continue;
            } else if (obj1[attr] !== obj2[attr]) {
                return false;
            }
        }
        return true;
    }

    【判断对象类型】

    // 对象类型
    function is(type, obj) {
        var clas = Object.prototype.toString.call(obj).slice(8, -1);
        return obj !== undefined && obj !== null && clas === type;
    }

    【防抖】

    export function debounce(func, wait, immediate) {
        let timeout, args, context, timestamp, result
    
        const later = function() {
            // 据上一次触发时间间隔
            const last = +new Date() - timestamp
    
            // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
            if (last < wait && last > 0) {
                timeout = setTimeout(later, wait - last)
            } else {
                timeout = null
                // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
                if (!immediate) {
                    result = func.apply(context, args)
                    if (!timeout) context = args = null
                }
            }
        }
    
        return function(...args) {
            context = this
            timestamp = +new Date()
            const callNow = immediate && !timeout
                // 如果延时不存在,重新设定延时
            if (!timeout) timeout = setTimeout(later, wait)
            if (callNow) {
                result = func.apply(context, args)
                context = args = null
            }
    
            return result
        }
    }

    【时间格式化】

    export function number2DateTime(value, fmt = 'yyyy-MM-dd HH:mm:ss') { // yyyy-MM-dd HH:mm:ss
        if (isNaN(value) || value == null) return '';
        const date = new Date(Number(value));
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hour = date.getHours();
        const minute = date.getMinutes();
        const second = date.getSeconds();
        return fmt.replace('yyyy', year.toString())
            .replace('yy', (year % 100).toString())
            .replace('MM', month > 9 ? month.toString() : ("0" + month))
            .replace('dd', day > 9 ? day.toString() : ("0" + day))
            .replace('HH', hour > 9 ? (hour).toString() : ("0" + hour))
            .replace('mm', minute > 9 ? (minute).toString() : ("0" + minute))
            .replace('ss', second > 9 ? (second).toString() : ("0" + second));
    }

    【去掉空格】

    export function trim(str) { // 去空格
        if(str == null) return
        return str.replace(/s/g, '');
    }

    【距离当前多少天】

    /**
     * @description 距离现在多少天
     * @params { String } dateStr 比如 2010-12-12 12:34:21
    */
    export function getDaysFromNow(dateStr) {
        let d = new Date();
        let dEnd = new Date(`${d.getFullYear()}-${(d.getMonth() + 1)}-${d.getDate()} 00:00:00`).getTime();
    
        let ds = new Date(dateStr);
        let dStart = new Date(`${ds.getFullYear()}-${(ds.getMonth() + 1)}-${ds.getDate()} 00:00:00`).getTime();
    
        let dSpan = Math.abs(dEnd - dStart);
    
        return Math.floor(dSpan / (24 * 3600 * 1000));
    }
  • 相关阅读:
    网页中的默认按钮
    心动不如行动
    周日骑行广州大学城
    买单车别买重车
    今晚好无聊
    在自行车论坛看到的有趣帖子
    php zend framework 生成 pdf 出现中文乱码
    FPDI Import existing PDF documents into FPDF
    PHP 哈希表,关联数组,遍历方法大全
    zend framework 如何多表查询
  • 原文地址:https://www.cnblogs.com/MonaSong/p/11857051.html
Copyright © 2011-2022 走看看