MediumNo. 2776LeetCode Premium

Convert Callback Based Function to Promise Based Function — LeetCode 2776 Python Solution

Topics
JavaScript
Reading time
4 min

The problem

Write a function that accepts another function fn and converts the callback-based function into a promise-based function. The function fn takes a callback as its first argument, along with any additional arguments args passed as separate inputs.

Example

Example
function sum(callback, a, b) {
  if (a < 0 || b < 0) {
    const err = Error('a and b must be positive');
    callback(undefined, err);
  } else {
    callback(a + b);
  }
}

Python solution

PythonSolution
import asyncio


def promisify(fn):
    async def wrapped(*args):
        loop = asyncio.get_running_loop()
        future = loop.create_future()

        def callback(value=None, err=None):
            if future.done():
                return
            if err is not None:
                future.set_exception(err)
            else:
                future.set_result(value)

        fn(callback, *args)
        return await future

    return wrapped

Complexity

Time
O(1)excluding the wrapped function
Space · auxiliary
O(1)

Related problems

Related problems
No.ProblemDifficulty
2778Sum of Squares of Special ElementsEasy
0057Insert IntervalMedium
0192Word FrequencyMedium
0193Valid Phone NumbersEasy
0194Transpose FileMedium
0195Tenth LineEasy

Frequently asked questions

How hard is LeetCode 2776. Convert Callback Based Function to Promise Based Function?

LeetCode 2776. Convert Callback Based Function to Promise Based Function is rated Medium on LeetCode.

What is the time complexity of LeetCode 2776. Convert Callback Based Function to Promise Based Function?

The Python solution on this page runs in O(1) excluding the wrapped function.

What is the space complexity of LeetCode 2776. Convert Callback Based Function to Promise Based Function?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2776. Convert Callback Based Function to Promise Based Function cover?

LeetCode 2776. Convert Callback Based Function to Promise Based Function is tagged JavaScript on LeetCode.

Is LeetCode 2776. Convert Callback Based Function to Promise Based Function a premium problem?

Yes. LeetCode 2776. Convert Callback Based Function to Promise Based Function is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.