Higher-order folder function using callbacks

Viewed 50

I want to write a function that given a list of functions, will fold across that list, progressively passing in the result from each closure into the next one.

The function signature of the functions in the list would be something like (pseudo-code):

typealias DoneClosure = (Dictionary) -> Void
typealias Middleware = (Dictionary, DoneClosure) -> Void

I would have a list of type Middleware and I want to reduce from left to right, folding across the list and passing the result of each closure into the next closure.

let middleware1 = { acc, done in
    // do something with acc, modify it
    done(acc)
}

Each function would look similar to this, they'd modify the accumulator in some way and then pass the result to the done or next function.

What I'm looking for is a recursive function that can fold across the list using callbacks so it can be processed async. Can anyone help me out? (Language is irrelevant but JS or Swift is preferred).

2 Answers
Related