一些常用的工具函数合集

some tool functions

Posted by markzhang on March 8, 2019

拍平数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let flatten1 = (arr) => {
    return arr.reduce((prev, cur) => {
        return prev.concat(Array.isArray(cur) ? flatten(cur) : cur);
    }, []);
};

let flatten2 = (arr) => {
    let res = [];
    arr.forEach((item) => {
        if (Array.isArray(item)) {
            res.push(...flatten2(item));// push方法能直接改变原数组;concat不会改变,会生成一个新数组
        } else {
            res.push(item);
        }
    });
    return res;
};

操作cookie

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
CookieUtil = {
    addCookie: function(name, value, options={}) {
        var str = '';
        str += name + '=' + value;
        if (options.expires) {
            var date = new Date();
            var milliSeconds = date.getTime();
            date.setTime(milliSeconds + options.expires * 60 * 60 * 1000);
            options.expires = date.toGMTString();
        }
        for(x in options) {
            str += ';' + x + '=' + options[x];
        }
        document.cookie = str;
    },

    queryCookie: function(name) {
        var reg = new RegExp(name+'=(\\S*)');
        var res = reg.exec(document.cookie);
        if (res) {
            return res[1];
        } else {
            return '';
        }
    },

    deleteCookie: function(name) {
        this.addCookie(name, '', {expires: 0});
    }
};

深拷贝

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function deepClone(target, isDeep) {
    if (!target) return undefined;
    if (typeof target != 'object') return target;
    if (Array.isArray(target)) {
        if (isDeep) {
            return target.map(function(item) {
                return deepClone(item, true);
            });
        }
        return [].concat(target);
    } else {
        if (isDeep) {
            var obj = {};
            Object.keys().forEach(function(item) {
                obj[item] = deepClone(target[item], true);
            });
            return obj;
        }
        return {...target};
    }
}

数组去重

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Array.prototype.distinct1 = function() {
    var res = [],
        repeat = []
        nanFlag = true;
    this.forEach((item, index) => {
        if (this.indexOf(item) == index) {
            res.push(item);
        } else {
            if (item != item && nanFlag) {
                nanFlag = false;// 防止结果集存入多个NaN
                res.push(item);
            } else {
                repeat.push(item);
            }
        }
    });
    return res;
};

Array.prototype.distinct2 = function() {
    return [...new Set(this)];
};

debounce

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 简易版本
function debounce(func, wait) {
    var timer = 0;
    return function(...args) {
        timer && clearTimeout(timer);
        timer = setTimeout(function() {
            func.apply(this, args);
        }, wait);
    }
}

// 第一次可以立即触发的版本
function debounce(func, wait, immediate) {
    var timer, context, args;
    var later = function() {
        timer = setTimeout(function() {
            func.apply(context, args);
        }, wait);
    };
    return function(...params) {
        context = this, args = params;
        if (!timer) {
            if (immediate) {
                func.apply(context, args);
            }
            later();
        } else {
            clearTimeout(timer);
            later();
        }
    }
}

节流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 节流,让函数按照一定间隔来执行,一定时间内执行指定次数
function throttle(func, wait) {
    var timer = 0;
    return function(...params) {
        if (timer) return;
        timer = setTimeout(function() {
            func.apply(this, params);
            timer = 0;
        }, wait);
    }
}

// 第一次调用会立即执行的节流函数
function throttle(func, wait, first) {
    var timer;
    return function(...params) {
        if (first) {
            first = false;
            func.apply(this, params);
        }
        if (!timer) {
            timer = setTimeout(function() {
                func.apply(this, params);
            }, wait);
        }
    }
}