• Typescript Daily
  • Posts
  • Faced with unknown problem in interview? - Follow these simple steps.

Faced with unknown problem in interview? - Follow these simple steps.

Take small steps towards the goal in order to complete it.

📢 Special Note to Our Readers

If your friends have sent you this newsletter over email, please consider subscribing here so that you get every day’s content direct to your inbox.

🎯 Typescript Daily Digest section in this newsletter typically includes tips, use cases, features, and basically anything related to typescript. For this weekly edition, we thought to include a frontend problem solving interview-style content. Please let us know in your feedback if this is good. If yes, we can continue this every week with a new topic. Also, feel free to suggest different topics/content to cover. You can directly reply to this email to provide your feedback to share your valuable suggestions, feedback, and questions.

Okay, let’s dive into this weekly edition article.

🎯 TypeScript Daily Digest! (Special Edition)

For this weekly edition, let’s take a real-world front-end problem that’s been asked frequently in problem-solving rounds.

Let’s implement a Custom Promise from scratch using vanilla Typescript.

Just for clarity, actual promise usage looks something like below:

const promise = new Promise((resolve: Function, reject: Function) => {});

// Usage
promise.then((data: any) => {}).catch((error: any)=> {}).finally((data: any) => {});

Similar to the above, the question is to implement a polyfill for the Promise, so that, the following is possible and behaves the same way as Promise.

const customPromise = new CustomPromise((resolve: Function, reject: Function) => {});

// Usage
customPromise.then((data: any) => {}).catch((error: any)=> {}).finally((data: any) => {});

How to approach this question if you are not sure about the implementation?

Let’s say you are asked this question in the interview round and you’ve not done such a polyfill implementation for Promise before.

You tend to get anxious already thinking about the result of the interview not going in your favor.

While that’s possible, you still have time to try different things. I would suggest to remove that thought from your mind. Focus on the problem at hand.

  1. Can we narrow down the scope of the problem considering the interview time? [Promise has a lot of things (Promise.all, Promise.resolve, Promsie.reject, …)]. You definitely won’t be able to implement everything given the short span of time.

  2. What do you already know about Promises and how they are used?

  3. What concepts from the JS/TS fundamentals you can start applying here?

  4. Also, start interacting with the interviewer about the things that you are brainstorming.

Not just for this question, you can actually use these pointers for any question. It doesn’t guarantee you any winning result but will make sure to help you try all the possible approaches before deciding to give up.

NOTE: If you give up very soon during any interview, it gets viewed as a flag. On the other hand, if you struggle a lot and try different approches but eventually fail to give the correct result, at least this time, the interviewer will value this as a good trait and consider helping or assisting in many occassions.

Having all of these in mind, let’s try to solve this problem.

Can we narrow down the scope of the problem considering the interview time?

Yes. Let’s check with the interviewer if it is ok to concentrate on the following aspects:

  1. .then handling

  2. .catch handling

  3. .finally handling

  4. Actual promise (resolve, reject)

Most of the time, the interviewer should be okay for you to implement just these as these would already give them a rough idea of your understanding of the concepts.

What do you already know about Promises and how they are used?

You know that Promises are classes (in a way). You provide a callback function to its constructor during initialization. Something like below:

const promise = new Promise(callback);

So, how can you achieve this part alone?

All we need is a class and the constructor needs to take an argument which is a function. Let’s try to build that:

class Custom {
    constructor(arg: Function) {}
}

Simple, now we have already gotten started with our implementation.

As you think about this step, communicate this with your interviewer. Keep doing this as you progress during your interview.

NOTE: Don’t remain silent for too long.

What concepts from the JS/TS fundamentals you can start applying here?

If you look closely at the promise handling of then, catch, finally:

promise.then( ... ).catch( ... ).finally( ... )

What can you see here?

It is a simple function chaining in Javascript. It’s even easier to implement if you have classes. You just have to return this.

class Custom {
    constructor(arg: Function) {}

    then(data: any) {
        // Actual logic

        // Adding this helps you chain all public methods.
        return this;
    }

    catch(error: any) {
        // Actual logic

        // Adding this helps you chain all public methods.
        return this;
    }

    finally(data: any) {
        // Actual logic

        // Adding this helps you chain all public methods.
        return this;
    }
}

Now, we have a basic implementation of then, catch, and finally. Of course, we still have not handled the code logic inside it.

If you look at your current progress now from how you were before you started? You’re actually doing a pretty good job!

From now on, it gets a little tricky. You need to think a little out-of-the-box to achieve the following:

const promiseMethod = (resolve: Function, reject: Function) => {
 // logic
}

const promise = new Promise(promiseMethod);

If you look at the above code, the Promise constructor is called with a function promiseMethod which in-turn takes 2 arguments resolve, and reject.

The first question is:

How will you get a hold of resolve and reject to be able to use inside our Custom Class?

If you can answer this, you have solved the problem.

There is something called .bind in Javascript. What it does is bind a function with scope and some arguments for it to be called later with those updated sets of values and scope. The same holds true for using .call, .apply or directly calling the function with different arguments.

const promiseMethod = (resolve: Function, reject: Function) => {
 // logic
}

const promise = new Promise(promiseMethod);

Taking this as an example again, we can invoke the promiseMethod from inside the constructor by passing our own dummy methods for resolve and reject. These methods will be called during the flows. Applying this to our custom class, we get the following:

type PromiseArg = (resolve: Function, reject: Function) => void;

class Custom {
    constructor(executableMethod: PromiseArg) {
        const resolve = (data: any) => {
            // logic
        };

        const reject = (error: any) => {
            // logic
        };

        executableMethod(resolve, reject); // Binds our resolve and reject
    }

    then(data: any) {
        // Actual logic

        // Adding this helps you chain all public methods.
        return this;
    }

    catch(error: any) {
        // Actual logic

        // Adding this helps you chain all public methods.
        return this;
    }

    finally(data: any) {
        // Actual logic

        // Adding this helps you chain all public methods.
        return this;
    }
}
const resolve = (data: any) => {
            // logic
        };

        const reject = (error: any) => {
            // logic
        };

        executableMethod(resolve, reject); // Binds our resolve and reject

This part takes care of the invocations to the passed method. Whenever resolve or reject is invoked by the caller, our methods get invoked. This gives us control over the flow.

Now, we can go ahead and implement the rest of the logic for then, catch, and finally.

Hope this style of approach gives you a bit of an idea when you face a problem that you have no idea about. You can take small steps in the right direction to reach your target.

Below is the fully-fledged implementation of the Custom Promise in case you are interested in the implementation as well. This includes things like Promises state, Invocations, then, catch, finally, and passing down the data.

🏁 Wrapping It Up

Another day, another dive into the world of TypeScript. As we cross the finish line today, remember to keep exploring, keep learning, and most importantly, keep coding. If you found value in today's insights, please consider sharing this newsletter with friends or on social media — every share helps us reach more TypeScript enthusiasts like you! Stay tuned for tomorrow's journey.

Reply

or to participate.