Skip to content

Commit 8262e9e

Browse files
committed
Merge branch 'HEAD' of git@github.com:kvz/phpjs.git
2 parents f32c804 + 4daf370 commit 8262e9e

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

_workbench/strings/similar_text.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
function similar_text (first, second) {
2+
/*
3+
* This is a direct port from PHP source code with a few modifications. May be buggy.
4+
* This function still needs to be checked and unit tested.
5+
* Other goals are to switch from recursive to iterative approach
6+
*
7+
* Original by: Rafał Kukawski
8+
*/
9+
var pos1 = 0, pos2 = 0, max = 0,
10+
firstLength = first.length, secondLength = second.length,
11+
p, q, l, sum;
12+
13+
max = 0;
14+
15+
for (p = 0; p < firstLength; p++) {
16+
for(q = 0; q < secondLength; q++) {
17+
for (l = 0; (p + l < firstLength) && (q + l < secondLength) && (first.charAt(p + l) === second.charAt(q + l)); l++);
18+
if (l > max) {
19+
max = l;
20+
pos1 = p;
21+
pos2 = q;
22+
}
23+
}
24+
}
25+
26+
sum = max;
27+
28+
if (sum) {
29+
if (pos1 && pos2) {
30+
sum += similar_text(first.substr(0, pos2), second.substr(0, pos2));
31+
}
32+
33+
if ((pos1 + max < firstLength) && (pos2 + max < secondLength)) {
34+
sum += similar_text(first.substr(pos1 + max, firstLength - pos1 - max), second.substr(pos2 + max, secondLength - pos2 - max));
35+
}
36+
}
37+
38+
return sum;
39+
}
40+

0 commit comments

Comments
 (0)