Skip to content

Instantly share code, notes, and snippets.

@HuangXiZhou
Created April 18, 2018 20:07
Show Gist options
  • Save HuangXiZhou/e491859558b6d4c066af2ef8b7fee9b2 to your computer and use it in GitHub Desktop.
Save HuangXiZhou/e491859558b6d4c066af2ef8b7fee9b2 to your computer and use it in GitHub Desktop.
Javascript Lazyman
// Class create
class Lazyman {
constructor(name) {
this.task = [];
const fn = () => {
console.log(`Hi! This is ${name}`);
this.next();
}
this.task.push(fn);
setTimeout(() => {
this.next();
}, 0);
}
next() {
const fn = this.task.shift();
fn && fn();
}
sleepFirst(time) {
const fn = () => {
setTimeout(() => {
console.log(`Wake up after ${time}`);
this.next();
}, time * 1000);
}
this.task.unshift(fn);
return this;
}
sleep(time) {
const fn = () => {
setTimeout(() => {
console.log(`Wake up after ${time}`);
this.next();
}, time * 1000);
}
this.task.push(fn);
return this;
}
eat(type) {
const fn = () => {
console.log(`Eat ${type}~`);
this.next()
}
this.task.push(fn);
return this;
}
}
// Run Lazyman
const lazyman = (name) => new Lazyman(name);
// Example
lazyman('hank').eat('dinner').sleep('3');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment