I required a do/while loop for navigating a paginated website, and have a proposal for how this could be made a generically available function.
It is implemented by initially creating an arbitrarily large number of iterations that represents the maximum (current default 100), and at each step adding two "then" steps. The first can perform actions such as navigation and waiting for the next page, the second can also perform some actions but MUST return a boolean to decide whether to continue the iteration.
If the condition function ever returns false, then a "thenBypassIf" step skips all remaining iterations.
Is there any interest in adding this to the core library?
// Coffeescript
doWhile = (preAction, condition, maxIter=100) ->
for current in [0...maxIter]
do (current) ->
casper.then(preAction)
casper.then(->
return_value = condition()
casper.log("return = " + return_value, "warning")
casper.log("current = " + current, "warning")
casper.thenBypassIf(! return_value, 2 * (maxIter - current - 1)))
// Compiled Javascript
doWhile = function(preAction, condition, maxIter = 100) {
var current, j, ref, results;
results = [];
for (current = j = 0, ref = maxIter; (0 <= ref ? j < ref : j > ref); current = 0 <= ref ? ++j : --j) {
results.push((function(current) {
casper.then(preAction);
return casper.then(function() {
var return_value;
return_value = condition();
casper.log("return = " + return_value, "warning");
casper.log("current = " + current, "warning");
return casper.thenBypassIf(!return_value, 2 * (maxIter - current - 1));
});
})(current));
}
return results;
};
// Quick test method.
i = 0;
doWhile(function() {
return casper.log("preAction is here", "warning");
}, function() {
casper.log("i = " + i++, "warning");
return i <= 10;
});