JavaScript

Lesson 05

Array transformations

Use array methods to make collection changes readable and avoid accidental mutation.

Good Code

changed-files.js
function summarizeChangedFiles(files) {
  // The pipeline returns new summary objects instead of changing input.
  return files
    .filter((file) => file.status !== "deleted")
    .map((file) => ({
      path: file.path,
      churn: file.additions + file.deletions,
    }))
    .sort((left, right) => right.churn - left.churn);
}

Bad Code

changed-files.js
function summarizeChangedFiles(files) {
  // Sorting and assigning churn mutate data other code may still use.
  files.sort((left, right) => right.additions - left.additions);

  const summary = [];

  files.forEach((file) => {
    if (file.status !== "deleted") {
      file.churn = file.additions + file.deletions;
      summary.push(file);
    }
  });

  return summary;
}

Review Notes

What to review

Good Code

The good version reads like a pipeline: remove deleted files, shape each item, then sort the new summaries by churn.

Bad Code

The bad version mutates the original array order and adds churn onto existing file objects, which can surprise other code that still holds those references.

Takeaways

  • Prefer filter, map, and reduce when they describe the transformation without mutating input data.