Description
JavaScript is single-threaded, yet we often need to control the execution order of asynchronous tasks.
In real-world apps, libraries and frameworks internally maintain task queues to schedule work in a predictable order.
This challenge simulates that idea by building a chainable API that schedules and prioritizes tasks.
You’ll implement a function LazyMan(name) that supports chained methods like:
- eating food
- sleeping for some time
- prioritizing a task to run before everything else
The tricky part is ensuring the entire chain finishes building before execution begins, and that sleepFirst() always runs before previously scheduled tasks.
Your Task
Implement a function LazyMan(name) that returns a chainable object supporting:
Method | Description |
|---|---|
LazyMan(name) | Immediately schedules a greeting task. |
eat(food) | Schedules a task to log eating the given food. |
sleep(seconds) | Delays the next task by given seconds. |
sleepFirst(seconds) | Delays execution before all other tasks (highest priority). |
Requirements
Your implementation must ensure:
- Tasks execute in the correct order.
- All chained calls finish before execution begins.
sleepFirst()runs before all other tasks even if called last.- Methods must be chainable.
- Execution must be asynchronous (non-blocking).
Examples
Input
LazyMan("Hank")Expected Output
Hi I am HankExample 2
Input
LazyMan("Hank").eat("dinner")Expected Output
Hi I am Hank
Eat dinnerExample 3 (Priority Case)
Input
LazyMan("Hank")
.eat("dinner")
.sleep(2)
.sleepFirst(1)Expected Output
// waits 1 second
Wake up after 1s
Hi I am Hank
Eat dinner
// waits 2 seconds
Wake up after 2sExpected Behavior
- Tasks are queued internally and executed sequentially.
sleepFirst()inserts a task at the front of the queue.- Execution begins only after the call stack becomes empty.
- Supports unlimited chaining.