I often find myself coding a loop where I fetch some data and the loop depends on whether there was any data left. Those loops must always be entered at least once (because we always need the first check for more data).
In JS we currently have two
while
structures for this. Neither seem to suffice for this case:
var data = fetch();
while (data) {
process(data);
data = fetch(); // duplication!
}
do {
var data = fetch();
if (data) { // duplication! (the while checks it too)
process(data);
}
} while(data);
I'd like to be able to do this:
repeat {
var data = fetch();
} while (data) {
process(data);
}
Yes, that's not necessarily shorter but it's very clear and concise. It's to the point. It also prevents code duplication in
way more complex cases, where either the fetch or the condition is more than the simple expression in the examples above.
The code will always enter the
repeat
block. It then tests the
while
condition. If the condition is false, the structure is exited completely. Otherwise the
while
block is entered followed by the
repeat
block again. Loop as usual.
So this is just a
do .. while
with conditional
while
body.
And even though I really wouldn't mind this kind of structure in JS, it's almost sad that I don't even wanna try to propse this on es-discuss. Meh.
/edit
I guess I should mention a workable workaround (thanks
Alexander ;):
for(;;){ // repeat
var data = fetch();
if (!data) break; // while
process(data);
}
My biggest beef with this is the inverted
while
condition and maybe that I'd prefer to have code that _reads_ a little better :)