Created
May 16, 2020 02:33
-
-
Save nemoinho/bd57669f509bb0ba32d12b1b8e08e021 to your computer and use it in GitHub Desktop.
A simple and naive implementation of diff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function naiveDiff(aIn, bIn, options) { | |
const rawA = aIn + '' === aIn ? aIn.split('') : aIn; | |
const rawB = bIn + '' === bIn ? bIn.split('') : bIn; | |
let a = rawA; | |
let b = rawB; | |
if (options.trim) { | |
a = a.map(s => s.trim()); | |
b = b.map(s => s.trim()); | |
} | |
if (options.skipEmpty) { | |
a = a.filter(s => s !== ''); | |
b = b.filter(s => s !== ''); | |
} | |
const m = a.length; | |
const n = b.length; | |
let start = 0; | |
while (start <= m && start <= n && a[start] == b[start]) { | |
start++; | |
} | |
let m_end = m - start; | |
let n_end = n - start; | |
while (start <= m_end && start <= n_end && a[m_end] == b[n_end]) { | |
m_end--; | |
n_end--; | |
} | |
const c = Array(m_end+1).fill(0).map(x => Array(n_end+1).fill(0)); | |
for (let i = 1; i <= m_end; i++) { | |
for (let j = 1; j <= n_end; j++) { | |
if (a[i-1+start] == b[j-1+start]) { | |
c[i][j] = c[i-1][j-1] + 1; | |
} else { | |
c[i][j] = Math.max(c[i][j-1], c[i-1][j]); | |
} | |
} | |
} | |
const out = []; | |
for (let i = m_end, j = n_end; (i >= 0 && j > 0) || (i > 0 && j >= 0); ) { | |
if (i > 0 && j > 0 && a[i-1+start] == b[j-1+start]) { | |
out.push({action: 0, value: a[i-1+start]}); | |
i--; | |
j--; | |
} else if (j > 0 && (i === 0 || c[i][j-1] >= c[i-1][j])) { | |
out.push({action: 1, value: b[j-1+start]}); | |
j--; | |
} else if (i > 0 && (j === 0 || c[i][j-1] < c[i-1][j])) { | |
out.push({action: -1, value: a[i-1+start]}); | |
i--; | |
} | |
} | |
return rawA.slice(0, start) | |
.map(value => ({action: 0, value})) | |
.concat(out.reverse()) | |
.concat(rawA.slice(start+m_end).map(value => ({action: 0, value}))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment