Created
June 2, 2015 11:59
-
-
Save vidul-nikolaev-petrov/c19c1d40d2694105ce48 to your computer and use it in GitHub Desktop.
Soundex in JavaScript
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
/** | |
* Soundex in JavaScript | |
* | |
* @example | |
* // returns 'H416' | |
* soundex('Heilbronn'); | |
* | |
* @example | |
* // returns 'L222' | |
* soundex('Lissajous'); | |
* | |
* @example | |
* // returns 'S532' | |
* soundex('Soundex'); | |
* | |
* @param {String} string | |
* @return {String} result | |
*/ | |
function soundex(string) { | |
if (!string) return; | |
string = string.toUpperCase(); | |
var result = [string[0]], | |
max_length = 4, | |
current_char, | |
rules = { | |
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 | |
}; | |
for (var i = 1, len = string.length; i < len && result.length < max_length; i++) { | |
current_char = rules[string[i]]; | |
if (current_char && string[i] != string[i - 1]) { | |
result.push(current_char); | |
} | |
} | |
for (var i = 0, len = result.length; i < max_length - len; i++) { | |
result.push(0); | |
} | |
return (result.join('')); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment