文章 评论 浏览 29
订阅发布、任务机制(异步串行)
const _sayHi = Symbol('_sayHi') // 私有 class LazyManClass { constructor(name) { this.name = name this[_sayHi](name) this.handlerQueue = [] this.tasks = [] setTimeout(() => this.runTasks()) } [_sayHi](name) { console.log('Hi I am ' + name) } // 异步串行 runTasks() { const len = this.tasks.length const next = (i) => { if(i==len) return this.tasks[i](() => next(i+1)) } next(0) } clear() { this.handlerQueue = [] } run() { this.handlerQueue.forEach((fn) => fn()) this.clear() } sleep(time) { this.run() const task = (cb) => { console.log('等待了' + time + '秒') setTimeout(() =>{ this.run() cb() }, time*1000) } this.tasks.push(task) return this } eat(food) { this.handlerQueue.push(() => console.log('I am eating' + food)) return this } sleepFirst(time) { const queue = [...this.handlerQueue] const task = (cb) => { console.log('等待了' + time + '秒') setTimeout(() =>{ queue.forEach((fn) => fn()) cb() }, time*1000) } this.tasks.push(task) this.handlerQueue = [] return this } } function LazyMan(name) { return new LazyManClass(name); } // LazyMan('Tony'); // LazyMan('Tony').sleep(3).eat('lunch'); // LazyMan('Tony').eat('lunch').sleep(3).eat('dinner') LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(2).sleep(3).eat('junk food');
@xiongchenf 兄弟,你用了sort之后时间复杂度已经是O(nlog(n))了,不符合题目O(log(m+n))
文章 0 评论 0
接受
订阅发布、任务机制(异步串行)
第 56 题:要求设计 LazyMan 类,实现以下功能