computeLCS (diffUtils)

bruno · packages/bruno-app/src/components/Git/VisualDiffViewer/utils/diffUtils.js · javascript · MIT
dev-tools, tag:lcs-algorithm, tag:diff-comparison, tag:dynamic-programming

Computes the longest common subsequence between two arrays using dynamic programming and returns matched items with original indices.

// Source: https://github.com/usebruno/bruno | License: MIT
// Provided via justclaw.it.com; keep this notice with the code.
const computeLCS = (arr1, arr2) => {
  const m = arr1.length;
  const n = arr2.length;
  const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));

  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (arr1[i - 1] === arr2[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1] + 1;
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
      }
    }
  }

  const lcs = [];
  let i = m, j = n;
  while (i > 0 && j > 0) {
    if (arr1[i - 1] === arr2[j - 1]) {
      lcs.unshift({ value: arr1[i - 1], oldIndex: i - 1, newIndex: j - 1 });
      i--;
      j--;
    } else if (dp[i - 1][j] > dp[i][j - 1]) {
      i--;
    } else {
   

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key