memoize.wxs 973 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * Simple memoize
  3. * wxs doesn't support fn.apply, so this memoize only support up to 2 args
  4. */
  5. function isPrimitive(value) {
  6. var type = typeof value;
  7. return (
  8. type === 'boolean' ||
  9. type === 'number' ||
  10. type === 'string' ||
  11. type === 'undefined' ||
  12. value === null
  13. );
  14. }
  15. // mock simple fn.call in wxs
  16. function call(fn, args) {
  17. if (args.length === 2) {
  18. return fn(args[0], args[1]);
  19. }
  20. if (args.length === 1) {
  21. return fn(args[0]);
  22. }
  23. return fn();
  24. }
  25. function serializer(args) {
  26. if (args.length === 1 && isPrimitive(args[0])) {
  27. return args[0];
  28. }
  29. var obj = {};
  30. for (var i = 0; i < args.length; i++) {
  31. obj['key' + i] = args[i];
  32. }
  33. return JSON.stringify(obj);
  34. }
  35. function memoize(fn) {
  36. var cache = {};
  37. return function() {
  38. var key = serializer(arguments);
  39. if (cache[key] === undefined) {
  40. cache[key] = call(fn, arguments);
  41. }
  42. return cache[key];
  43. };
  44. }
  45. module.exports.memoize = memoize;