memoize.wxs 986 B

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