EasyJavaScriptTypeScript

Avoid Side Effects

TypeScriptClean CodePure FunctionsRefactoring

The function below mutates its input array — a classic source of bugs.

// dirty — mutates the original array!
interface CartItem { name: string; price: number; }

function solve(cart: CartItem[], item: CartItem): CartItem[] {
  cart.push(item);
  cart.sort((a, b) => a.price - b.price);
  return cart;
}

Refactor `solve(cart, item)` so it returns a new sorted array without modifying cart.

After calling solve(cart, item), the original cart array must be unchanged.

Sample tests

Test #1Returns new sorted array with item added
Input: [[{"name":"B","price":20},{"name":"A","price":10}],{"name":"C","price":5}]
Output: [{"name":"C","price":5},{"name":"A","price":10},{"name":"B","price":20}]
Test #2Works with empty cart
Input: [[],{"name":"Solo","price":99}]
Output: [{"name":"Solo","price":99}]
Test #3Equal prices preserve relative order (stable sort)
Input: [[{"name":"X","price":50}],{"name":"Y","price":50}]
Output: [{"name":"X","price":50},{"name":"Y","price":50}]