Instacart: decide on replacements before an item runs out
Instacart lets people order store items online for a shopper to pick up. Its replacement preferences let customers say in advance what they would accept when an item is unavailable, and when they would prefer a refund.
Break down the problem and try your own design and implementation first. Then explore the reasoning to check states, edge cases, trade-offs, and ways to test your approach. The guide offers a reasoning path, not a complete implementation.
01
CODE EXERCISE
Resolve replacement preferences in one place
Implement a function that resolves a grocery cart’s current replacement preference. Both the display and order submission call it so that they use the same interpretation of defaults.
- Inputs: resolvePreference(orderChoice, savedChoice). Each argument is null or one of the strings best, specific and refund, meaning unset, best match, specific replacement and refund. Inputs are valid. Resolve only the preference type; do not store specific replacement products.
- Rules: Use orderChoice when it is not null. Otherwise use savedChoice when it is not null. If both are null, use best. Return {choice, origin}, with the selected type in choice and order, saved or default in origin to identify its source. Do not modify inputs or store state. refund is a valid choice, not a missing value.
- Checks: (refund, best) returns {choice:refund, origin:order}; (null, refund) returns {choice:refund, origin:saved}; (null, null) returns {choice:best, origin:default}; (best, refund) returns {choice:best, origin:order}.
- Deliver: Implement the function in a language you know, run the four examples, and briefly explain how display and submission share the policy. No page, account or order placement is needed.
Explore the reasoning
- Establish the priority of the three sources and decide where source selection happens, so display and submission do not each implement it.
- Only null means unset. An explicit refund is as valid as either other choice.
- Trace both the selected type and its origin through all four examples, especially whether an explicit best overrides a saved refund.