非クロージャ版
HTML
<ul>
<li><a href="https://teratail.com/questions/122987">JavaScript - 再帰関数を引数に取りそれを実行する高階関数のコンテキストを変数巻き上げを使わずに変える方法(122987)|teratail</a></li>
</ul>
JavaScript
'use strict';
/**
* do-while版
*/
function sample1 (fn, continuefn, fnargs, thisArgs) {
let condition;
thisArgs = Array.isArray(thisArgs) ? thisArgs : [];
do {
for (let i = 0, length = fn.length; i < length; ++i) {
fn[i].apply(thisArgs[i], fnargs);
}
condition = continuefn(...fnargs);
fnargs = condition[1];
} while (condition[0])
}
/**
* 再帰版
*/
function sample2 (fn, continuefn, fnargs, thisArgs) {
thisArgs = Array.isArray(thisArgs) ? thisArgs : [];
for (let i = 0, length = fn.length; i < length; ++i) {
fn[i].apply(thisArgs[i], fnargs);
}
const condition = continuefn(...fnargs);
if (condition[0]) {
sample2(fn, continuefn, condition[1], thisArgs);
}
}
function fn1 () {
console.log('-----');
}
function fn2 (number, string) {
console.log(string.repeat(number));
}
function conditionfn (number, ...args) {
return [number > 0, [--number, ...args]];
}
sample1([fn1, fn2], conditionfn, [5, '#']);
sample2([fn1, fn2], conditionfn, [5, '#']);