关于javascript:js代码片段-utilslcoalStoragecookie

43次阅读

共计 5379 个字符,预计需要花费 14 分钟才能阅读完成。

utils 工具函数

/**
 * Finding all the occurrences of an element in Array
 * @returns {Array}
 */
indexOfAll = function (array, element) {var indices = [], idx;
    idx = array.indexOf(element);
    while (idx !== -1) {indices.push(idx);
        idx = array.indexOf(element, idx + 1);
    }
    return indices;
};

/**
 * Calculate the length of object
 * @returns {int}
 */
obLength = function (map) {
    var key, count = 0;
    for (key in map) {if (map.hasOwnProperty(key)) {count += 1;}
    }
    return count;
};

/**
 * Judge the string if it is numeric. Only for decimal.
 * @returns {boolean}
 */
isNumeric = function (value) {return (/^-?([0-9]+(.[0-9]+)?|Infinity)$/).test(value);
};

/**
 * Return the unique elements of one array, remove redundant elements
 * @return {Array}
 */
unique = function (opt) {var a = [], l = opt.length, i, j;
    for (i = 0; i < l; i += 1) {for (j = i + 1; j < l; j += 1) {// If opt[i] is found later in the array
            if (opt[i] === opt[j]) {
                i += 1;
                j = i;
            }
        }
        a.push(opt[i]);
    }
    return a;
};

/**
 * Get the random color for css
 * @return {string}
 */
getRandomColor = function () {
    var letters, color = "#", i, str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F";
    letters = str.split(",");
    for (i = 0; i < 6; i += 1) {color += letters[Math.round(Math.random() * 15)];
    }
    return color;
};

/**
 * Transform timestamp to format "HH:mm:ss.l DD-MM-YY"
 * @returns {string}
 */
timeStampToString = function (timeStamp) {
    var fmt, oShow, oDate;
    timeStamp = (typeof timeStamp === "string") ? parseFloat(timeStamp) : timeStamp;
    fmt = function (n, m) {
        m = m || 10;
        return (m === 100 && n < 10) ? "00" + n : (n < m ? "0" + n : n);
    };

    oDate = new Date(timeStamp);
    oShow = fmt(oDate.getDate()) + "-" + fmt(oDate.getMonth() + 1) + "-" + oDate.getFullYear() + "" + fmt(oDate.getHours()) +":"+ fmt(oDate.getMinutes()) +":"+ fmt(oDate.getSeconds()) +"." + fmt(oDate.getMilliseconds(), 100);
    return oShow;
};

/**
 * Display the huge number in human readable text
 * @returns {string}
 */
shortHugeNumber = function (num) {
    var returnNum, million = 1000000, billion = 1000000000, mValue, bValue, secNum, fstNum;

    num = (typeof num !== "number") ? parseFloat(num) : num;
    bValue = parseFloat((num / billion).toFixed(3));
    mValue = parseFloat((num / million).toFixed(3));

    if (bValue > 1.000) {returnNum = bValue + "billion";} else if (bValue === 1.000) {returnNum = "one billion";} else if (mValue > 1.000) {returnNum = mValue + "million";} else if (mValue === 1.000) {returnNum = "one million";} else if (num >= 1000) {
        returnNum = "/" + num;
        fstNum = returnNum.substring(1, returnNum.length - 3) + ",";
        secNum = returnNum.substring(returnNum.length - 3, returnNum.length);
        returnNum = fstNum + secNum;
    } else {returnNum = num;}

    return returnNum;
};

/**
 * Get the current clock
 * @return {string}
 */
getClock = function () {

    var tDay, tMonth, d, nDay, nMonth, nDate, nYear, nHour, nMin, nSec, nClock;
    tDay = ["Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"];
    tMonth = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    d = new Date();
    nDay = d.getDay();
    nMonth = d.getMonth();
    nDate = d.getDate();
    nYear = d.getYear();
    nHour = d.getHours();
    nMin = d.getMinutes();
    nSec = d.getSeconds();

    if (nYear < 1000) {nYear = nYear + 1900;}
    if (nMin <= 9) {nMin = "0" + nMin;}
    if (nSec <= 9) {nSec = "0" + nSec;}
    nClock = tDay[nDay] + "," + nDate + "" + tMonth[nMonth] +" "+ nYear +" "+ nHour +":"+ nMin +":" + nSec;
    return nClock;
}

/**
 * Readable file size
 * @param fileSizeInBytes
 * @returns {string}
 */
getReadableFileSize = function (fileSizeInBytes) {
    var i = -1;
    var byteUnits = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    fileSizeInBytes = parseInt(fileSizeInBytes, 10);
    do {
        fileSizeInBytes = fileSizeInBytes / 1024;
        i++;
    } while (fileSizeInBytes > 1024);

    return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
}

Cookie 的二次封装

/**
 * Cookie 的二次封装
 */
class ServiceCookie {
    /**
     * 全副
     * @returns {{}}
     */
    getAllCookieValue() {const cookie = {};
        const all = document.cookie;
        if (all === '') {return cookie;}
        const list = all.split(';');
        list.forEach((item) => {const keyAndName = item.split('=');
            cookie[keyAndName[0]] = decodeURIComponent(keyAndName[1]) || '';
        });
        return cookie;
    }

    /**
     * 提取数据
     * @param key
     * @returns {*}
     */
    getItem(key) {const cookie = this.getAllCookieValue();
        return cookie[key] || null;
    }

    /**
     * 存储数据
     * @param key
     * @param value
     * @param maxAge
     * @param path
     */
    setItem(key, value, maxAge, path) {if (value === undefined) {this.removeItem(key);
        } else {let newCookie = `${key}=${encodeURIComponent(value)}`;
            if (maxAge) newCookie += `; max-age=${maxAge}`;
            if (path) newCookie += `; path=${path}`;
            document.cookie = newCookie;
        }
    }

    /**
     * 删除数据
     * @param key
     */
    removeItem(key) {const cookie = this.getAllCookieValue();
        if (!(key in cookie)) {return;}
        document.cookie = `${key}=; max-age=0`;
    }
}

export default new ServiceCookie();

localStorage 的二次封装,存储 JSON 格局数据

/**
 * localStorage 的二次封装,存储 JSON 格局数据
 */
class ServiceStorage {
    /**
     * constructor
     */
    constructor() {
        this.instance = {
            local: localStorage,
            session: sessionStorage,
        };
    }

    /**
     * 存储数据
     * @param key
     * @param value
     * @param type
     * @returns {*}
     */
    setItem(key, value, type = 'local') {if (value === undefined) {this.removeItem(key);
        } else {this.instance[type].setItem(key, this.serialize(value));
        }
    }

    /**
     * 提取数据
     * @param key
     * @param type
     * @returns {*}
     */
    getItem(key, type = 'local') {return this.deserialize(this.instance[type].getItem(key));
    }

    /**
     * 删除数据
     * @param key
     * @param type
     */
    removeItem(key, type = 'local') {this.instance[type].removeItem(key);
    }

    /**
     * 清空数据
     * @param type
     */
    clearItems(type = 'local') {this.instance[type].clear();}

    /**
     * 数据列表
     * @param type
     * @returns {{}}
     */
    getAllItems(type = 'local') {const res = {};
        let i;
        let key;
        for (i = 0; i < this.instance[type].length; i += 1) {key = this.instance[type].key(i);
            res[key] = this.getItem(key);
        }
        return res;
    }

    /**
     * 输入 JSON 格局数据
     * @returns {string}
     */
    serialize(value) {return typeof value === 'object' ? JSON.stringify(value) : value;
    }

    /**
     * 解码 JSON 数据
     * @param value
     * @returns {*}
     */
    deserialize(value) {if (typeof value !== 'string') {return undefined;}
        try {return JSON.parse(value);
        } catch (e) {return value || undefined;}
    }

    /**
     * 查找数据存在性
     * @param key
     * @returns {boolean}
     *
     */
    checkItem(key) {const token = this.getItem(key);
        return (!(token === undefined || token === null));
    }
}

export default new ServiceStorage();

正文完
 0