A `buffer` might work better here. I'm afraid working on array is quite inefficient: each resize operation does an array copy.

While a `fold` is quite elegant, I'm wondering if a more imperative solution wouldn't be clearer. Up to you.