一看就是好代碼的代碼(不斷更新中)

緩存

        function repush(array, item) {前端

            // 對存在的item,更新到最後web

            // 用ii加速for循環緩存

            for (var i = 0, ii = array.length; i < ii; i++)app

                if (array[i] === item) {函數

                    return array.push(array.splice(i, 1)[0]);post

                }ui

        }this


        function cacher(f, scope, postprocessor) {spa

            // f是生成緩存的函數prototype

            // scope是f的域

            // postprocessor是處理舊緩存的函數

            // --------------------------------------

            // 1e3是lru隊列的量,用短路方法(&&)執行

            function newf() {

                var arg = Array.prototype.slice.call(arguments, 0),

                    args = arg.join("\u2400"),

                    cache = newf.cache = newf.cache || {},

                    count = newf.count = newf.count || [];

                if (cache.hasOwnProperty(args)) {

                    repush(count, args);

                    return postprocessor ? postprocessor(cache[args]) : cache[args];

                }

                count.length >= 1e3 && delete cache[count.shift()];

                count.push(args);

                cache[args] = f.apply(scope, arg);

                return postprocessor ? postprocessor(cache[args]) : cache[args];

            }

            return newf;

        }

兼容amd cmd export

(function(root, factory) {

    if (typeof define === 'function' && define.amd) {

        define([], factory);

    } else if (typeof exports === 'object') {

        module.exports = factory();

    } else if (typeof define === "function" && define.cmd) {

        define(function(require, exports, module) {

            module.exports = factory();

        });

    } else {

        root.Sword = factory();

    }

}(this, function() {

}))


前端冷知識什錦

http://web.jobbole.com/83473/

相關文章
相關標籤/搜索