From f432571bbe1df69d1f80c0a67f8922e6c58592ad Mon Sep 17 00:00:00 2001 From: neverland Date: Tue, 11 Dec 2018 17:32:53 +0800 Subject: [PATCH] [improvement] memoize bem (#1054) --- packages/wxs/memoize.wxs | 52 ++++++++++++++++++++++++++++++++++++++++ packages/wxs/utils.wxs | 8 +++++-- 2 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 packages/wxs/memoize.wxs diff --git a/packages/wxs/memoize.wxs b/packages/wxs/memoize.wxs new file mode 100644 index 00000000..3e624274 --- /dev/null +++ b/packages/wxs/memoize.wxs @@ -0,0 +1,52 @@ +/** + * Simple memoize + * wxs doesn't support fn.apply, so this memoize only support up to 2 args + */ + +function isPrimitive(value) { + var type = typeof value; + return ( + type === 'boolean' || + type === 'number' || + type === 'string' || + type === 'undefined' || + value === null + ); +} + +// mock simple fn.call in wxs +function call(fn, args) { + if (args.length === 2) { + return fn(args[0], args[1]); + } + + if (args.length === 1) { + return fn(args[0]); + } + + return fn(); +} + +function serializer(args) { + if (args.length === 1 && isPrimitive(args[0])) { + return args[0]; + } + + return JSON.stringify(args.length === 1 ? args[0] : args); +} + +function memoize(fn) { + var cache = {}; + + return function() { + var key = serializer(arguments); + + if (cache[key] === undefined) { + cache[key] = call(fn, arguments); + } + + return cache[key]; + }; +} + +module.exports.memoize = memoize; diff --git a/packages/wxs/utils.wxs b/packages/wxs/utils.wxs index a1ac7674..5deffee0 100644 --- a/packages/wxs/utils.wxs +++ b/packages/wxs/utils.wxs @@ -1,8 +1,12 @@ var bem = require('./bem.wxs').bem; +var memoize = require('./memoize.wxs').memoize; function isSrc(url) { return url.indexOf('http') === 0 || url.indexOf('data:image') === 0; } -module.exports.bem = bem; -module.exports.isSrc = isSrc; +module.exports = { + bem: memoize(bem), + isSrc: isSrc, + memoize: memoize +};