[underscore 源码学习] delay 延迟执行函数 -

2020-01-29  本文已影响0人  小黄人get徐先生

延迟执行函数 delay

_.delay(function, wait, *arguments)
    _.delay = function(func, wait) {
        const args = [].slice.call(arguments, 2);
        return setTimeout(function() {
           // 将参数赋予 func 函数
           return func.apply(null, args);
        }, wait);
    };

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>underscore</title>
</head>
<body>
    <script src="./test.js"></script>
    <script>
        _.delay(function () {
            console.log('console after 1500');
        }, 1500);
    </script>
</body>
</html>

函数组合 compose

_.compose(*functions)
    _.compose = function() {
        const funcList = [].slice.call(arguments);

        return function(val) {
            return _.reduceRight(funcList, function(memo, func) {
                return func(memo);
            }, val);
        }
    };
    // 或
    _.compose = function() {
        const args = arguments;
        const start = args.length - 1;

        return function() {
            let i = start;
            let result = args[start].apply(this, arguments);
            while (i--) result = args[i].call(this, result);
            return result;
        }
    };

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>underscore</title>
</head>
<body>
    <script src="./test.js"></script>
    <script>
        function a(val) {
            return val * 2;
        }
        function b(val) {
            return val + 2;
        }
        function c(val) {
            return val - 2;
        }
        console.log(_.compose(a, b, c)(5));
    </script>
</body>
</html>

escape 字符串逃逸(防止 XSS 攻击)

转义字符
_.escape(string)
    const escapeMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#x27;',
        '`': '&#x60;'
    };

    const createEscaper = function(map) {
        const escaper = function(match) {
            return map[match];
        };
        const source = '(?:' + Object.keys(map).join('|') + ')';
        const testRegExp = new RegExp(source, "g");
        return function(string) {
            return testRegExp.test(string) ? string.replace(testRegExp, escaper) : string;
        };
    };

    _.escape = createEscaper(escapeMap);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>underscore</title>
</head>
<body>
    <script src="./test.js"></script>
    <script>
        console.log(_.escape("<a>aaaaa"));
    </script>
</body>
</html>

显示结果如下:


上一篇 下一篇

猜你喜欢

热点阅读