Last active
July 18, 2020 06:34
-
-
Save lagagain/00a0d2a13314866a15629e38c99df068 to your computer and use it in GitHub Desktop.
This file contains 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
class Repeatable{ | |
static RUN = 0; | |
static BREAK = -1; | |
static CONTINUE = 1; | |
constructor(env = {}){ | |
this.i = 0; | |
this.env = env; | |
this._env = {...env}; | |
this.status = Repeatable.RUN; | |
} | |
repeat(fn, time){ | |
this.reset(); | |
fn = fn.bind(this); | |
let status = this.status; | |
for(;this.i < time; this.i++){ | |
console.debug(`status: ${status}`); | |
if (status === Repeatable.RUN || status === undefined){ | |
status = fn(); | |
} else if (status === Repeatable.CONTINUE){ | |
status = this.RUN; | |
continue; | |
} else if (status === Repeatable.BREAK){ | |
status = this.RUN; | |
break; | |
} else { | |
throw "WRONG STATUS"; | |
} | |
} | |
} | |
reset(){ | |
this.reset_idx(); | |
this.reset_env(); | |
} | |
reset_idx(){ | |
this.i = 0; | |
} | |
reset_env(){ | |
this.env = {...this._env}; | |
} | |
getIdx(){ | |
return this.i; | |
} | |
getVar(name){ | |
return this.env[name]; | |
} | |
} | |
const repeat = Repeatable.prototype.repeat.bind(new Repeatable()); | |
function hello(){ | |
let i = this.getIdx(); | |
console.log('hello', i); | |
if(i === 3){ | |
console.debug("continue"); | |
return Repeatable.CONTINUE; | |
} | |
if(i === 10){ | |
console.debug("break"); | |
return Repeatable.BREAK; | |
} | |
} | |
repeat(hello, 15); | |
function helloName(){ | |
let i = this.getIdx(); | |
let name = this.getVar("name")[i]; | |
console.log(`${i}: hello, ${name}!`); | |
} | |
new Repeatable({"name":["John", "Kity", "Ted"]}).repeat(helloName, 3); | |
_debug = console.debug; | |
console.debug = ()=>{}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment