Refactor while loop using map

Signed-off-by: Bebe Peng <b.peng@awesometown.local>