Untitled

mail@pastecode.io avatar
unknown
javascript
a month ago
996 B
1
Indexable
Never
  const pages = useAppSelector((state) => state.builder.pages.list);

  const currentPathname = location.pathname;

  let closestPage: Page | null = null;
  let minDistance = Infinity;

  function levenshteinDistance(s1, s2) {
    const m = s1.length;
    const n = s2.length;
    const dp = Array.from(Array(m + 1), () => Array(n + 1).fill(0));

    for (let i = 0; i <= m; i++) {
      for (let j = 0; j <= n; j++) {
        if (i === 0) {
          dp[i][j] = j;
        } else if (j === 0) {
          dp[i][j] = i;
        } else if (s1[i - 1] === s2[j - 1]) {
          dp[i][j] = dp[i - 1][j - 1];
        } else {
          dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
        }
      }
    }

    return dp[m][n];
  }

  pages.forEach((page) => {
    const distance = levenshteinDistance(page.url, currentPathname);
    if (distance < minDistance) {
      minDistance = distance;
      closestPage = page;
    }
  });

  console.log("closestPage", closestPage);
Leave a Comment