Turn a discount loop into a pipeline
Refactor a mixed discount loop into a readable map/filter/reduce pipeline.
A cart discount loop mutates totalDiscount, pushes display rows, skips expired coupons, and increments warning counts in one pass. Collection Pipeline: filter selects, map transforms, reduce accumulates. The novice move is to convert the loop to one giant reduce with side effects. That keeps the same hidden jobs and makes the functional version harder to review. Step 1 Extract isApplicableCoupon(coupon, cart, asOf) and build applicableCoupons = coupons.filter(...). Selection gets its own predicate, so expired and ineligible coupons can be tested without pricing logic. Step 2 Create discountLines = applicableCoupons.map(coupon => toDiscountLine(coupon, cart)). Transformation turns each qualifying coupon into a displayable…
Sign up free — one personalized lesson every day, matched to your role and goals.
Already have an account? Sign in