Skip to content

Instantly share code, notes, and snippets.

@421p
Last active June 12, 2022 22:21
Show Gist options
  • Select an option

  • Save 421p/2a32a5aa7cd1ed4bb55413ca34c1b0c3 to your computer and use it in GitHub Desktop.

Select an option

Save 421p/2a32a5aa7cd1ed4bb55413ca34c1b0c3 to your computer and use it in GitHub Desktop.

Revisions

  1. 421p revised this gist Feb 26, 2017. 1 changed file with 6 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions usage.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    export class Foo{
    @memoize get bar()
    {
    return 1 + 1; // will be calculated once and then cached
    }
    }
  2. 421p revised this gist Feb 26, 2017. No changes.
  3. 421p created this gist Feb 26, 2017.
    20 changes: 20 additions & 0 deletions memoize.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    export function memoize(target: any, prop: string, descriptor: PropertyDescriptor)
    {
    let original = descriptor.get;

    descriptor.get = function (...args: any[])
    {
    const privateProp = `__memoized_${prop}`;

    if (!this.hasOwnProperty(privateProp)) {
    Object.defineProperty(this, privateProp, {
    configurable: false,
    enumerable: false,
    writable: false,
    value: original.apply(this, args)
    });
    }

    return this[privateProp];
    };
    }