JavaScript is not capable of supporting continuations: it lacks tail calls.
In general, I would write this to use the “queue” in sorts, although CPS is also do-able (it just has a finite stack :-) Note that another state can also be captured in closure, which makes it “explicitly continue” in a very rude sense.
An example of using closure and queue:
function prodFactory (array){ // dupe array first if needed, is mutated below. // function parameters are always locally scoped. array.unshift(undefined) // so array.shift can be at start // also, perhaps more closured state var otherState // just return the real function, yippee! return function prod () { array.shift() // do stuff ... eg loop array.shift() and multiply // set otherState ... eat an apple or a cookie return stuff } } var prod = prodFactory([1,2,3,0,4,5,0,6,7,8,0,9]) // array at "do stuff", at least until "do stuff" does more stuff prod() // [1,2,3,0,4,5,0,6,7,8,0,9] prod() // [2,3,0,4,5,0,6,7,8,0,9] prod() // [3,0,4,5,0,6,7,8,0,9]
Happy coding.
"Completed implementation." Although this particular problem can avoid mutating the array and just use the index: the same concepts apply. (Well, a little different. Only with the index the private variable will be changed, whereas with this approach the object will mutate.)
function prodFactory (array) { array = array.slice(0) return function prod () { var p = 1 for (var n = array.shift(); n; n = array.shift()) { p *= n } return p } } var prod = prodFactory([1,2,3,0,4,5,0,6,7,8,0,9]) prod()