refactor duplicate folding code into one method