How to measure time of function using js proxy

Viewed 9

I would like to measure time of my all function in my class Foo.

My code is:

class Foo {
    constructor() {
        return new Proxy(this, {
            get(target, prop, receiver) {
                console.log(`Calling '${prop}'`); 
                return target[prop];
            },
        });
    }

    myFn() {
        console.log('hi');
    }
}

new Foo().myFn();

Problem is, that I need to return function from proxy. I tried to use code return () => target[prop](); but it looks like that myFn was not called.

Any tips? Maybe can I achieve it using rxjs lib?

1 Answers

In your code above, if you are looking for myFn() to return a value, then you need to include a return statement in myFn(). You can see that myFn() did run as the console did log the 'hi' message.

In the example snippet below, you can see that anotherFn() has a return statement, and thus the Proxy is returning what that method returned.

Keep in mind that if you use a static method, like the staticFn() in the snippet, the Class does not need to be instantiated with a new, and the constructor will not be triggered, not logging that method.

class Foo {
  constructor() {
    return new Proxy(this, {
      get(target, prop, receiver) {
        console.log(`Calling '${prop}'`);
        return target[prop];
      },
    });
  }
  myFn() {
    console.log('hi');
  }
  anotherFn(string) {
    return string
  }
  static staticFn(message) {
    return message
  }
}

console.log({
  myFn: new Foo().myFn(),
  anotherFn: new Foo().anotherFn('hello'),
  staticFn: Foo.staticFn('world')
})

Related