Refactored hard-to-read d3 code