84cc9b9bf1a3c0f6c767a1ff3f2535ae2618da4b
4 var MAX_MATRIX_SIZE
= 256 * 256;
6 function createMatrix(i
, j
) {
7 return new Uint32Array(i
* j
);
10 function levenshteinMatrix(s
, t
) {
11 /** Calculate the Levenshtein edit distance matrix for two strings
13 The matrix is returned as a flat unsigned typed array.
15 Following http://en.wikipedia.org/wiki/Levenshtein_distance
19 var d
= createMatrix(m
, n
);
21 for (i
= 1; i
< m
; ++i
)
23 for (j
= 1; j
< n
; ++j
)
25 for (j
= 1; j
< n
; ++j
)
26 for (i
= 1; i
< m
; ++i
)
27 if (s
[i
- 1] === t
[j
- 1])
28 d
[n
* i
+ j
] = d
[n
* (i
- 1) + j
- 1];
30 d
[n
* i
+ j
] = 1 + Math
.min(d
[n
* (i
- 1) + j
],
32 d
[n
* (i
- 1) + j
- 1]);
36 function editPath(d
, s
, t
) {
37 /** Given a Levenshtein result matrix, trace the shortest edit */
43 var sub
= (i
&& j
) ? d
[n
* (i
- 1) + j
- 1] : Infinity
;
44 var del
= i
? d
[n
* (i
- 1) + j
] : Infinity
;
45 var ins
= j
? d
[n
* i
+ j
- 1] : Infinity
;
46 if (sub
<= ins
&& sub
<= del
) {
47 if (d
[n
* i
+ j
] !== d
[n
* (i
- 1) + j
- 1])
48 path
.push(["sub", i
- 1, t
[j
- 1]]);
50 } else if (ins
<= del
) {
51 path
.push(["ins", i
, t
[j
- 1]]);
54 path
.push(["del", i
- 1]);
61 function applyEdits(edits
, s
) {
62 /** Apply the list of edits to s */
64 for (i
= 0; i
< edits
.length
; ++i
) {
68 s
= s
.slice(0, edit
[1]) + edit
[2] + s
.slice(edit
[1] + 1);
71 s
= s
.slice(0, edit
[1]) + edit
[2] + s
.slice(edit
[1]);
74 s
= s
.slice(0, edit
[1]) + s
.slice(edit
[1] + 1);
81 function slowLerp(a
, b
, p
) {
82 /** Interpolate between two strings slowly
84 This interpolation algorithm applys a partial edit of one
85 string into the other. This produces nice looking results,
86 but can take a significant amount of time and memory to
87 compute the edits. It is not recommended for strings
88 longer than a few hundred characters.
90 var edits
= editPath(levenshteinMatrix(a
, b
), a
, b
);
91 var partial
= edits
.slice(0, Math
.round(p
* edits
.length
));
92 return applyEdits(partial
, a
);
95 function fastLerp(a
, b
, p
) {
96 /** Interpolate between two strings very quickly
98 This interpolation algorithm progressively replaces the
99 front of one string with another. This approach is fast
100 but does not look good when the strings are similar.
102 var alen
= Math
.round(a
.length
* p
);
103 var blen
= Math
.round(b
.length
* p
);
104 return b
.substring(0, blen
) + a
.substring(alen
, a
.length
);
107 function lerp(a
, b
, p
) {
110 var n
= a
.length
* b
.length
;
111 // TODO: if both strings are integers, do an integer lerp.
112 // TODO: if both strings are numbers, do a numeric lerp.
113 return (n
&& n
< MAX_MATRIX_SIZE
)
118 exports
.levenshteinMatrix
= levenshteinMatrix
;
119 exports
.editPath
= editPath
;
120 exports
.fastLerp
= fastLerp
;
121 exports
.slowLerp
= slowLerp
;
122 exports
.applyEdits
= applyEdits
;
125 })(typeof exports
=== "undefined" ? (this.stringLerp
= {}) : exports
);