refactored scan and reduce with a builder to remove duplicated code