SHARE
TWEET

Untitled

a guest Apr 23rd, 2019 94 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. type _map = Map<string, any>;
  2. let weakMap = new WeakMap<Function, _map>();
  3.  
  4. type f = (...args: any[]) => any;
  5. type c = new (...args: any[]) => any;
  6. type t<F extends f | c> = F extends f
  7.     ? ReturnType<F>
  8.     : F extends c
  9.     ? InstanceType<F>
  10.     : never;
  11. type p<F extends f | c> = F extends f
  12.     ? Parameters<F>
  13.     : F extends c
  14.     ? ConstructorParameters<F>
  15.     : never;
  16.  
  17. const isConstructor = (Foo: f | c): Foo is c => {
  18.     if (Foo &&
  19.         Foo.prototype &&
  20.         Foo.prototype.constructor
  21.     ) { return true; }
  22.     return false;
  23. }
  24.  
  25. function memorise<F extends f | c, T = t<F>, P = p<F>>(f: F, args: P): T {
  26.     if (!args) throw new Error('!args');
  27.     let res: T;
  28.     if (weakMap.has(f)) {
  29.         let map = weakMap.get(f);
  30.         // --------------------------------------------
  31.         let a1 = JSON.stringify(args)
  32.         for (let [a0, resC] of map) {
  33.             if (a1 === a0) {
  34.                 res = resC;
  35.                 break;
  36.             }
  37.         }
  38.     } else {
  39.         if (isConstructor(f)) {
  40.             //@ts-ignore
  41.             res = new f(...args);
  42.         } else {
  43.             //@ts-ignore
  44.             res = f(...args);
  45.         }
  46.         let _map: _map = new Map();
  47.         _map.set(JSON.stringify(args), res);
  48.         weakMap.set(f, _map);
  49.     }
  50.     return res;
  51. }
  52.  
  53. test_1: {
  54.     const increment = (q: number) => (console.count('increment'), q + 1);
  55.     let res = memorise(increment, [7]);
  56.     console.log(res === memorise(increment, 7)); // true
  57.     console.log(res); // 8
  58. }
  59.  
  60. test_2: {
  61.     const sum = (a: number, b: number) => (console.count('sum'), a + b);
  62.     let res = memorise(sum, [7, 11]);
  63.     console.log(res === memorise(sum, [7, 11])); // true
  64.     console.log(res); // 18
  65. }
  66.  
  67. test_3: {
  68.     class Point {
  69.         constructor(
  70.             public x: number,
  71.             public y: number,
  72.             public z: number,
  73.         ) { }
  74.     }
  75.     let res = memorise(Point, [1, 2, 3]);
  76.     console.log(res === memorise(Point, [1, 2, 3])); // true
  77.     console.log(res instanceof Point); // true
  78.     console.log(res); // Point {x: 1, y: 2, z: 3}
  79. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top