Skip to main content

Turn a discount loop into a pipeline

Refactor a mixed discount loop into a readable map/filter/reduce pipeline.

functional-programming5 min read

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…

Read the full lesson

Sign up free: one personalized lesson every day, matched to your role and goals.

← Back to library

Contact us