refactor recursive function