Simple email application for Android. Original source code: https://framagit.org/dystopia-project/simple-email
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.6 KiB

  1. 'use strict';
  2. const mimicFn = require('mimic-fn');
  3. const isPromise = require('p-is-promise');
  4. const mapAgeCleaner = require('map-age-cleaner');
  5. const cacheStore = new WeakMap();
  6. const defaultCacheKey = (...args) => {
  7. if (args.length === 0) {
  8. return '__defaultKey';
  9. }
  10. if (args.length === 1) {
  11. const [firstArgument] = args;
  12. if (
  13. firstArgument === null ||
  14. firstArgument === undefined ||
  15. (typeof firstArgument !== 'function' && typeof firstArgument !== 'object')
  16. ) {
  17. return firstArgument;
  18. }
  19. }
  20. return JSON.stringify(args);
  21. };
  22. module.exports = (fn, options) => {
  23. options = Object.assign({
  24. cacheKey: defaultCacheKey,
  25. cache: new Map(),
  26. cachePromiseRejection: false
  27. }, options);
  28. if (typeof options.maxAge === 'number') {
  29. mapAgeCleaner(options.cache);
  30. }
  31. const {cache} = options;
  32. options.maxAge = options.maxAge || 0;
  33. const setData = (key, data) => {
  34. cache.set(key, {
  35. data,
  36. maxAge: Date.now() + options.maxAge
  37. });
  38. };
  39. const memoized = function (...args) {
  40. const key = options.cacheKey(...args);
  41. if (cache.has(key)) {
  42. const c = cache.get(key);
  43. return c.data;
  44. }
  45. const ret = fn.call(this, ...args);
  46. setData(key, ret);
  47. if (isPromise(ret) && options.cachePromiseRejection === false) {
  48. // Remove rejected promises from cache unless `cachePromiseRejection` is set to `true`
  49. ret.catch(() => cache.delete(key));
  50. }
  51. return ret;
  52. };
  53. mimicFn(memoized, fn);
  54. cacheStore.set(memoized, options.cache);
  55. return memoized;
  56. };
  57. module.exports.clear = fn => {
  58. const cache = cacheStore.get(fn);
  59. if (cache && typeof cache.clear === 'function') {
  60. cache.clear();
  61. }
  62. };