Created
February 10, 2022 03:16
-
-
Save navio/e99fd06c84d911a20753661a4e736a2b to your computer and use it in GitHub Desktop.
130 create-lazyman
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://bigfrontend.dev/problem/create-lazyman | |
// interface Laziness { | |
// sleep: (time: number) => Laziness | |
// sleepFirst: (time: number) => Laziness | |
// eat: (food: string) => Laziness | |
// } | |
/** | |
* @param {string} name | |
* @param {(log: string) => void} logFn | |
* @returns {Laziness} | |
*/ | |
function LazyMan(name, logFn) { | |
class Laziness { | |
messages = [] | |
queue = false; | |
constructor(name,fn){ | |
this.name = name; | |
this.fn = fn; | |
this.messages.push(`Hi, I'm ${this.name}.`); | |
this.display(); | |
return this; | |
} | |
eat(food){ | |
this.messages.push(`Eat ${food}.`); | |
this.display(); | |
return this; | |
} | |
sleep(time){ | |
this.messages.push(time); | |
this.display(); | |
return this | |
} | |
sleepFirst(time){ | |
this.messages.unshift(time); | |
this.display(); | |
return this | |
} | |
display(){ | |
const next = (element) => { | |
if(element){ | |
const nextElement = this.messages.shift(); | |
if(typeof element !== 'number'){ | |
this.fn(element); | |
next(nextElement); | |
}else{ | |
setTimeout(()=> { | |
const phrase = element === 1 ? | |
`Wake up after ${element} second.` : `Wake up after ${element} seconds.` | |
this.fn(phrase) | |
next(nextElement); | |
}, element * 1000); | |
} | |
} | |
} | |
if(!this.queue){ | |
this.queue = true; | |
setTimeout(()=>{ | |
const element = this.messages.shift(); | |
next(element) | |
}); | |
} | |
} | |
} | |
return new Laziness(name, logFn); | |
} | |
// LazyMan('Jack', console.log).eat('banana').sleepFirst(10).eat('apple').sleep(1) | |
// LazyMan('Jack', console.log).eat('banana').eat('apple').sleepFirst(2) | |
LazyMan('Jack', console.log).eat('banana').sleepFirst(10).eat('apple').sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment