Skip to content

Instantly share code, notes, and snippets.

@RichardBray
Created July 3, 2024 13:47
Show Gist options
  • Save RichardBray/e63f4ae1b2b2448bc4f650df967c4a24 to your computer and use it in GitHub Desktop.
Save RichardBray/e63f4ae1b2b2448bc4f650df967c4a24 to your computer and use it in GitHub Desktop.

Revisions

  1. RichardBray created this gist Jul 3, 2024.
    39 changes: 39 additions & 0 deletions decorators.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    function log(originalMethod: any, _context: any) {
    function replacementMethod(this: any, ...args: any[]) {
    // const startTime = performance.now();
    console.log(`${originalMethod.name} START`);
    const result = originalMethod.call(this, ...args);
    console.log(`${originalMethod.name} END`);
    // const endTime = performance.now();
    // console.log(`Method ${originalMethod.name} took ${endTime - startTime} milliseconds`);
    return "result: " + result;
    }

    return replacementMethod;
    }

    class Animal {
    #name: string;

    constructor(name: string) {
    this.#name = name;
    }

    get name() {
    return this.#name;
    }

    @log
    makeSound(): string {
    // let sound = "Sound";
    console.log("running makeSound");
    // if (this.#name === "Dog") sound = "Bark";
    // return sound;
    return "Sound";
    }
    }

    const animal = new Animal("Dog");
    const sound = animal.makeSound();

    console.log(sound);