Skip to content

Instantly share code, notes, and snippets.

@xtetsuji
Created June 21, 2023 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xtetsuji/d43b0b8d6a37346bfdf6153295a5d49b to your computer and use it in GitHub Desktop.
Save xtetsuji/d43b0b8d6a37346bfdf6153295a5d49b to your computer and use it in GitHub Desktop.
MajiDe time-based event driven interface by Japanese named class and its methods.
class MajiDe {
/**
* MajiDe オブジェクトを作成する
* @param {Function} func - コールバック
*/
constructor(func) {
if ( !func || typeof func !== "function" ) {
throw new Error("第一引数は関数にして下さい");
}
this.func = func;
}
/**
* MajiDe オブジェクトのコンストラクターに与えた関数を実行する待ち時間を単位無しで指定する
* @param {Number} time - このあとコールバックを実行する間隔
* @return {MajiDe} - return self for chain
*/
する(time) {
this.time = time;
return this;
}
/**
* この後の「(単位)前」メソッドで使われる内部メソッド
* @param {Number} unit - コンストラクターで与えた関数を実行する待ち時間の単位量をミリ秒基準で指定(秒なら1000など)
* @param {Array} arg - コンストラクターで与えた関数に与える引数。オプショナル
* @returns {Promise} - 待ち時間を待った後、コンストラクターで与えられた関数を実行後に解決される Promise
*/
単位前(unit, arg) {
if ( !this.time ){
throw new Error("「なんとか前」メソッドを呼ぶ前に「する」メソッドで単位を除いた待ち時間を指定して下さい");
}
if ( !unit ) {
throw new Error("第1引数で単位の倍数をミリ秒を基準に指定して下さい");
}
const waitms = (ms) => new Promise( resolve => setTimeout(resolve, ms) );
return waitms(this.time * unit).then( () => this.func(...arg) );
}
ミリ秒前(...arg) {
return this.単位前(1, arg);
}
秒前(...arg) {
return this.単位前(1000, arg);
}
分前(...arg) {
return this.単位前(1000 * 60, arg);
}
時間前(...arg) {
return this.単位前(1000 * 60 * 60, arg);
}
日前(...arg) {
return this.単位前(1000 * 60 * 60 * 24, arg);
}
}
const Majiで = (func) => new MajiDe(func);
const Koi = () => console.log("恋");
(async () => {
console.log("start");
await Majiで(Koi).する(5).秒前();
console.log("end");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment