I can't figure out the reason to do such a thing, thus I asked in a comment if this is a challenge.
Having experimented with loops/recursions couple days ago, your problem seemed like a good challenge to me. So, I'll provide a solution using recursion and try to be thorough.
Before writing a complex recursion loop, let's get the basics. First, let's try to write the following simple for loop with recursion:
for (var i = 0; i < 10; i++) {
console.log(i);
}
becomes
function customLoop(index, target, step, callback) {
if (index < target) {
callback(index);
index += step;
customLoop(index, target, step, callback);
}
}
customLoop(0, 10, 1, function (index) {
console.log(index);
});
Next, converting the for loop you provided into recursion:
for (let i = j = 999; j > 0; j > i ? j-- : i--) { console.log(i, j) }
becomes
function customLoop(a, b, callback) {
if (b > 0) {
callback(a, b);
if (a < b) {
b--;
} else {
a--;
}
customLoop(a, b, callback);
}
}
customLoop(50, 50, function (a, b) {
console.log(a, b);
});
Finally, writing a recursion that takes multiple values as indices. If you think of your values as a one-dimensional array, what you do, basically, is walk it two values at a time.
(I could draw a fancy graph to visualize this, but I don't have the time at the moment. So, maybe later.)
function customLoop(array, callback, startIndex) {
var startIndex = startIndex || 0;
if (startIndex < array.length - 1 && array[array.length - 1] > 0) {
var index_a = startIndex;
var index_b = index_a + 1;
var a = array[index_a];
var b = array[index_b];
if (callback) {
callback.apply(null, array);
}
if (a < b) {
array[index_b]--;
startIndex = index_b;
if (startIndex >= array.length - 1) {
startIndex = 0;
}
customLoop(array, callback, startIndex);
} else {
array[index_a]--;
customLoop(array, callback, startIndex);
}
}
}
customLoop([20, 20, 20, 20, 20], function (a, b, c, d, e) {
console.log(a, b, c, d, e);
});
You might need to tweak the code to make it fit your needs. Also, I don't about the performance of my solution. It might slower or faster than other solutions. So, test it out.