replace for loops with while loops to match Ramda style