Loops/While: Difference between revisions

No edit summary
Line 735:
=={{header|JavaScript}}==
<lang javascript>var n = 1024;
while (n > 0) {
print(n);
n /= 2;
}</lang>
 
In a functional idiom of JavaScript, however, we can not use a loop statement to achieve this task, as statements return no value, mutate state, and can not be composed within other functional expressions.
 
Instead, we can define a composable loopWhile() function which has no side effects, and takes 3 arguments:
:#An initial value
:#A function which returns some derived value
:#A conditional function
 
<lang JavaScript>function loopWhile(varValue, fnDelta, fnTest) {
'use strict';
var d = fnDelta(varValue);
 
return fnTest(d) ? [d].concat(
loopWhile(d, fnDelta, fnTest)
) : [d];
}
 
console.log(
loopWhile(
1024,
function (x) {
return x / 2
},
function (x) {
return x;
}
).join('\n')
);</lang>
 
=={{header|Joy}}==
9,659

edits