ORIGINAL TECHNICAL PRACTICE
Make input mutation an explicit contract
A helper sorts an array before calculating a result. What would you discuss before using it in a shared codebase?
Written for independent practice. The model answer presents one approach; clarify constraints and explain alternatives.
A REASONED APPROACH
Model answer.
Sorting may mutate the caller’s array, depending on the language and API. Decide whether mutation is intentional, document the contract, and use a copy when the caller’s order must remain available.
Work through it
- Inspect the language’s sorting API and comparator rules. In JavaScript, a numeric comparator is needed for numeric ascending order with Array.sort.
- If preserving input is required, copy the relevant data before sorting. A shallow copy protects the outer array’s order but not mutations to nested objects.
- Write tests that compare the original input before and after the call, as well as result correctness. Include repeated references and nested records when those are supported.
Tradeoffs to discuss
- Copying requires additional memory and time. An in-place API can be appropriate for large data when its ownership and mutation semantics are explicit.
Common pitfalls
- Assuming a shallow copy recursively clones records hides shared-object side effects. A comparator must be consistent; an inconsistent comparator can produce unreliable ordering.