Refactor pagination parts to separate function