Modifying a Function with a Diff Patch

Apply a unified diff patch that modifies an existing function by combining line removals and additions. Covers how '-' and '+' lines work together to represent edits.

Basic Patches

Detailed Explanation

Modifying Code with Combined Additions and Removals

Most real-world patches combine - (removal) and + (addition) lines to represent modifications. A line that is "changed" in the diff is actually shown as the old version removed and the new version added.

Example Original

function calculateTotal(items) {
  let total = 0;
  for (let i = 0; i < items.length; i++) {
    total += items[i].price;
  }
  return total;
}

Example Patch

--- a/calc.js
+++ b/calc.js
@@ -1,7 +1,5 @@
-function calculateTotal(items) {
-  let total = 0;
-  for (let i = 0; i < items.length; i++) {
-    total += items[i].price;
-  }
-  return total;
+function calculateTotal(items, taxRate = 0) {
+  const subtotal = items.reduce((sum, item) => sum + item.price, 0);
+  const tax = subtotal * taxRate;
+  return subtotal + tax;
 }

Understanding Modifications

There is no "modify" operation in unified diff format — only additions and removals. When a line is changed:

  1. The old version appears with a - prefix
  2. The new version appears with a + prefix

The patch engine removes all - lines and inserts all + lines at that position. The context line } at the end anchors the change to the correct location.

Grouping Convention

By convention, related removals and additions are grouped together. The removed block appears first, followed by the added block. This makes it easy to visually compare what changed when reading the diff.

Use Case

A team member refactored a function to use modern JavaScript features (arrow functions, reduce) and added a tax parameter. Apply their patch to update your local copy of the file.

Try It — Diff Patch Applier

Open full tool