[improvement] memoize bem (#1054)

This commit is contained in:
neverland 2018-12-11 17:32:53 +08:00 committed by GitHub
parent df238651c2
commit f432571bbe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 2 deletions

52
packages/wxs/memoize.wxs Normal file
View File

@ -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;

View File

@ -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
};