Skip to the solution
EasyLow-Level DesignAsked in 20246 min read

Wrap methods hook decorator

2.4k views

The problem

Problem, as an interviewer would state it: "Write withHooks(obj, { before, after }) — wrap EVERY method on obj so that a before hook fires just before each call, and an after hook fires just after, WITHOUT altering the method's own real behavior or return value."

Examples:

Code
const wrapped = withHooks(calculator, { before: logCall, after: logResult });
wrapped.add(2, 3); // logs before, runs add(2,3) normally, logs after, returns 5 unchanged

Clarifying questions expected:

  • Should non-function properties on the object be left untouched, or is this only for methods?
  • Does the wrapped method need to preserve the original this binding when called?
  • Should this handle an async method's hooks firing correctly relative to when the promise actually settles, not just when it is initially called?

Code / implementation expected: Yes — real, direct proof that both hooks fire correctly around real method calls, with return values passed through completely unchanged.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: before/after hooks fire correctly around every wrapped method call, with return values passed through completely unchanged

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 8 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Fetch wrapper auto-retry

Continue