Implementing LazyMan in JavaScript with Chainable Methods and Task Queue
This article explains the LazyMan interview problem, demonstrates how to build a JavaScript function supporting chainable sleep, eat, and sleepFirst methods using task queues, and provides step‑by‑step code implementations with explanations and visual results.
In the introduction, the author reflects on revisiting a classic interview question and its learning value.
The problem requires implementing a LazyMan function that accepts a name and supports chainable methods sleep , eat , and sleepFirst with specific execution order.
Initial implementation prints the greeting and returns an object with placeholder methods:
const LazyMan = (name) => {
console.log(`你好,我是${name}`);
return {
sleep(){},
eat(){},
sleepFirst(){}
};
};
LazyMan("Hank");To handle sleep(10) and eat('lunch') , the author adds a busy‑wait loop for sleep and logs the appropriate messages, returning the object for chaining.
const LazyMan = (name) => {
console.log(`你好,我是${name}`);
const lazyMan = {
sleep(second){
let startTime = Date.now();
while (Date.now() - startTime < 10000) {}
console.log(`我醒了,刚刚睡了${second}秒`);
return lazyMan;
},
eat(type){
console.log("吃午餐");
},
sleepFirst(){}
};
return lazyMan;
};
LazyMan("Hank").sleep(10).eat("lunch");For the eat method, a map translates food types to output strings, and the method returns the object to allow further chaining.
const eatInfoMap = { 'lunch': "吃午餐", 'supper': "吃晚餐" };
// inside lazyMan
eat(type){
console.log(eatInfoMap[type]);
return lazyMan;
}The sleepFirst method requires reordering execution, so the author introduces a task queue. Each method pushes a task function onto the queue; sleepFirst unshifts its task to the front. A next function dequeues and runs tasks sequentially, with setTimeout handling asynchronous delays.
const queue = [];
const next = () => {
const fn = queue.shift();
fn?.();
};
const lazyMan = {
sleep(s){
const task = () => {
setTimeout(() => { console.log(`我醒了,我刚睡了 ${s} 秒`); next(); }, s*1000);
};
queue.push(task);
return lazyMan;
},
eat(type){
const task = () => { console.log(eatInfoMap[type]); next(); };
queue.push(task);
return lazyMan;
},
sleepFirst(s){
const task = () => {
setTimeout(() => { console.log(`我醒了,我刚刚睡了 ${s} 秒`); next(); }, s*1000);
};
queue.unshift(task);
return lazyMan;
}
};
queue.push(() => { console.log(`你好,我是${name}`); next(); });
setTimeout(next, 0);
return lazyMan;Finally, the author runs the full solution and confirms that the output matches the expected order for all test cases, concluding the tutorial.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.