memoize.sjs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. var antmove_export = {};
  2. /**
  3. * Simple memoize
  4. * wxs doesn't support fn.apply, so this memoize only support up to 2 args
  5. */
  6. function isPrimitive(value) {
  7. var type = typeof value;
  8. return type === 'boolean' || type === 'number' || type === 'string' || type === 'undefined' || value === null;
  9. } // mock simple fn.call in wxs
  10. function call(fn, args, len) {
  11. if (len === 2) {
  12. return fn(args[0], args[1]);
  13. }
  14. if (len === 1) {
  15. return fn(args[0]);
  16. }
  17. return fn();
  18. }
  19. function serializer(args, len) {
  20. if (len === 1 && isPrimitive(args[0])) {
  21. return args[0];
  22. }
  23. var length = 0;
  24. if (args[1] !== undefined) {
  25. length = 2;
  26. } else if (args[0] !== undefined) {
  27. length = 1;
  28. }
  29. var obj = {};
  30. for (var i = 0; i < len; 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, arguments.length);
  39. if (cache[key] === undefined) {
  40. cache[key] = call(fn, arguments, arguments.length);
  41. }
  42. return cache[key];
  43. };
  44. }
  45. antmove_export.memoize = memoize;
  46. export default antmove_export;