memoize.sjs 940 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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 type === 'boolean' || type === 'number' || type === 'string' || type === 'undefined' || value === null;
  8. }
  9. // mock simple fn.call in wxs
  10. function call(fn, args) {
  11. if (args.length === 2) {
  12. return fn(args[0], args[1]);
  13. }
  14. if (args.length === 1) {
  15. return fn(args[0]);
  16. }
  17. return fn();
  18. }
  19. function serializer(args) {
  20. if (args.length === 1 && isPrimitive(args[0])) {
  21. return args[0];
  22. }
  23. var obj = {};
  24. for (var i = 0; i < args.length; i++) {
  25. obj['key' + i] = args[i];
  26. }
  27. return JSON.stringify(obj);
  28. }
  29. function memoize(fn) {
  30. var cache = {};
  31. return function () {
  32. var key = serializer(arguments);
  33. if (cache[key] === undefined) {
  34. cache[key] = call(fn, arguments);
  35. }
  36. return cache[key];
  37. };
  38. }
  39. module.exports.memoize = memoize;