Skip to content

Commit 28b50f9

Browse files
author
rafaelk
committed
Revised the algorithm for soundex calculation
1 parent 4fb27ee commit 28b50f9

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

functions/strings/soundex.js

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ function soundex (str) {
66
// + bugfixed by: Onno Marsman
77
// + input by: Brett Zamir (http://brett-zamir.me)
88
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
9-
// + bugfixed by: Rafał Kukawski (http://blog.kukawski.pl)
109
// + original by: Arnout Kazemier (http://www.3rd-Eden.com)
10+
// + revised by: Rafał Kukawski (http://blog.kukawski.pl)
1111
// * example 1: soundex('Kevin');
1212
// * returns 1: 'K150'
1313
// * example 2: soundex('Ellery');
@@ -16,21 +16,25 @@ function soundex (str) {
1616
// * returns 3: 'E460'
1717

1818
str = (str + '').toUpperCase();
19-
var sdx = [str.charAt(0), 0, 0 , 0],
20-
k = ['BFPV', 'CGJKQSXZ', 'DT', 'L', 'MN', 'R'], kl = k.length,
21-
i = 1, j = 0, s = 0, c, p;
19+
if (!str) {
20+
return '';
21+
}
22+
var sdx = [0, 0, 0, 0],
23+
m = {B: 1, F: 1, P: 1, V: 1, C: 2, G: 2, J: 2, K: 2, Q: 2, S: 2, X: 2, Z: 2, D: 3, T: 3, L: 4, M: 5, N: 5, R: 6},
24+
i = 0, j, s = 0, c, p;
2225

23-
while ((c = str.charAt(i++)) && s < 3 ){
24-
j = 0;
25-
while (p = k[j++]){
26-
if (p.indexOf(c) !== -1) {
27-
if (j !== sdx[s]){
28-
sdx[++s] = j;
29-
}
30-
break;
26+
while ((c = str.charAt(i++)) && s < 4) {
27+
if (j = m[c]) {
28+
if (j !== p) {
29+
sdx[s++] = p = j;
3130
}
31+
} else {
32+
s += i === 1;
33+
p = 0;
3234
}
3335
}
36+
37+
sdx[0] = str.charAt(0);
3438
return sdx.join('');
3539
}
3640

0 commit comments

Comments
 (0)