-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (71 loc) · 1.96 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// @flow
interface Enumerable<T> {
length: number;
[number]: T;
}
type Callback = (x1: number, y1: number, x2: number, y2: number) => void;
type Comparator<T> = (x: T, y: T) => boolean;
type Matrix = Array<Array<number>>;
function diff<T> (a: Enumerable<T>, b: Enumerable<T>, cmp: Comparator<T>): Matrix {
cmp = cmp || function (a, b) { return a === b }
var n = a.length
var m = b.length
var max = n + m
var v = Array(2 * max + 1)
var len = v.length
var trace = []
var k, x, y, addK, remK, _k
v[1] = 0
for (var d = 0; d <= max; d++) {
trace.push(v.slice(0))
for (k = -d; k <= d; k += 2) {
addK = k + 1 < 0 ? len - Math.abs(k + 1) : k + 1
remK = k - 1 < 0 ? len - Math.abs(k - 1) : k - 1
_k = k < 0 ? len - Math.abs(k) : k
if (k === -d || (k !== d && (v[remK] < v[addK]))) {
x = v[addK]
} else {
x = v[remK] + 1
}
y = x - k
while (x < n && y < m && cmp(a[x], b[y])) {
x = x + 1
y = y + 1
}
v[_k] = x
if (x >= n && y >= m) return trace
}
}
return trace
}
function tracePath<T> (a: Enumerable<T>, b: Enumerable<T>, cb: Callback, cmp: Comparator<T>) {
var x: number = a.length
var y: number = b.length
var k, addK, remK, prevX, prevY, prevK, _prevK
var shortestEdit: Matrix = diff(a, b, cmp)
for (var d = shortestEdit.length - 1; d >= 0; d--) {
var v: Array<number> = shortestEdit[d]
var len = v.length
k = x - y
addK = k + 1 < 0 ? len - Math.abs(k + 1) : k + 1
remK = k - 1 < 0 ? len - Math.abs(k - 1) : k - 1
if (k === -d || (k !== d && (v[remK] < v[addK]))) {
prevK = k + 1
_prevK = addK
} else {
prevK = k - 1
_prevK = remK
}
prevX = v[_prevK]
prevY = prevX - prevK
while (x > prevX && y > prevY) {
cb(x - 1, y - 1, x, y)
x = x - 1
y = y - 1
}
if (d > 0) cb(prevX, prevY, x, y)
x = prevX
y = prevY
}
}
export default tracePath