This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
130. create LazyMan()

Solution: One possible solution to implement LazyMan is by using a class and a chainable API. Here is the complete code:

class LazyMan {
  constructor(name, logFn) {
    this.queue = [];
    this.log = logFn;
    this.enqueue(`Hi, I'm ${name}.`);
    this.next();
  }

  enqueue(task) {
    this.queue.push(() => {
      this.log(task);
      this.next();
    });
  }

  eat(food) {
    this.enqueue(`Eat ${food}.`);
    return this;
  }

  sleep(seconds) {
    this.enqueue(`Sleeping for ${seconds} seconds...`);
    return this.wait(seconds * 1000);
  }

  sleepFirst(seconds) {
    this.queue.unshift(this.createWaitTask(seconds * 1000));
    return this;
  }

  wait(timeout) {
    this.queue.push(this.createWaitTask(timeout));
    return this;
  }

  createWaitTask(timeout) {
    return () => {
      setTimeout(() => {
        this.log(`Wake up after ${timeout / 1000} seconds.`);
        this.next();
      }, timeout);
    };
  }

  next() {
    const task = this.queue.shift();
    if (task) {
      task();
    }
  }
}

function lazyMan(name, logFn) {
  return new LazyMan(name, logFn);
}

The LazyMan class has four methods that correspond to the four possible actions: eat, sleep, sleepFirst, and wait. Each of these methods adds the corresponding task to a queue, which is executed sequentially by the next method. The enqueue method creates a task that logs a message and calls next. The createWaitTask method creates a task that waits for a given timeout and logs a wake-up message.

The sleepFirst method adds a wait task at the beginning of the queue, thus giving it the highest priority. The other methods use enqueue and wait to add their tasks to the end of the queue. The sleep method also returns this.wait to allow chaining with other methods.

Finally, the lazyMan function is a convenience function that creates a new instance of LazyMan. It can be used like this:

lazyMan('Jack', console.log)
  .eat('banana')
  .sleep(10)
  .eat('apple')
  .sleep(1);

lazyMan('Jack', console.log)
  .eat('banana')
  .sleepFirst(10)
  .eat('apple')
  .sleep(1);

Both examples will log the messages in the correct order, according to the actions taken by LazyMan.