Article From:https://www.cnblogs.com/mengfangui/p/9970356.html

1、source code

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>vueSource Cached Higher Order Function</title>
    </head>
    <body>
        <script type="text/javascript">
            function cached(fn) {
                console.log(fn,'fn')
                const cache = Object.create(null)
                // External cache -- closure is used in return function functions
                return (function cachedFn(str) {
                    console.log(str,'str');
                    const hit = cache[str]
                    console.log(hit, 'hit')
                    return hit || (cache[str] = fn(str))
                })
            }
            var capitalize = cached(function(str) {
                return str.charAt(0).toUpperCase() + str.slice(1)
            });
            console.log(capitalize,'capitalize')
            console.log(capitalize('abc'), 'For the first time')
            console.log(capitalize('abc'), 'The second time')
        </script>
    </body>
</html>

2、cachedFunction. The input parameter is a function and the return value is a function. Closure is also used.

Leave a Reply

Your email address will not be published. Required fields are marked *