--- id: 5a23c84252665b21eecc8017 title: Soundex challengeType: 5 --- ## Description
Soundex is an algorithm for creating indices for words based on their pronunciation. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from the WP article). There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules https://www.archives.gov/research/census/soundex.html. So check for instance if Ashcraft is coded to A-261. Write a function that takes a string as a parameter and returns the encoded string.
## Instructions
## Tests
``` yml tests: - text: soundex should be a function. testString: assert(typeof soundex == 'function', 'soundex should be a function.'); - text: soundex("Soundex") should return a string. testString: assert(typeof soundex("Soundex") == 'string', 'soundex("Soundex") should return a string.'); - text: soundex("Soundex") should return "S532". testString: assert.equal(soundex("Soundex"), "S532", 'soundex("Soundex") should return "S532".'); - text: soundex("Example") should return "E251". testString: assert.equal(soundex("Example"), "E251", 'soundex("Example") should return "E251".'); - text: soundex("Sownteks") should return "S532". testString: assert.equal(soundex("Sownteks"), "S532", 'soundex("Sownteks") should return "S532".'); - text: soundex("Ekzampul") should return "E251". testString: assert.equal(soundex("Ekzampul"), "E251", 'soundex("Ekzampul") should return "E251".'); - text: soundex("Euler") should return "E460". testString: assert.equal(soundex("Euler"), "E460", 'soundex("Euler") should return "E460".'); - text: soundex("Gauss") should return "G200". testString: assert.equal(soundex("Gauss"), "G200", 'soundex("Gauss") should return "G200".'); - text: soundex("Hilbert") should return "H416". testString: assert.equal(soundex("Hilbert"), "H416", 'soundex("Hilbert") should return "H416".'); - text: soundex("Knuth") should return "K530". testString: assert.equal(soundex("Knuth"), "K530", 'soundex("Knuth") should return "K530".'); - text: soundex("Lloyd") should return "L300". testString: assert.equal(soundex("Lloyd"), "L300", 'soundex("Lloyd") should return "L300".'); - text: soundex("Lukasiewicz") should return "L222". testString: assert.equal(soundex("Lukasiewicz"), "L222", 'soundex("Lukasiewicz") should return "L222".'); ```
## Challenge Seed
```js function soundex (s) { // Good luck! } ```
## Solution
```js function soundex (s) { var a = s.toLowerCase().split('') var f = a.shift(), r = '', codes = { a: '', e: '', i: '', o: '', u: '', 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 }; r = f + a .map(function(v, i, a) { return codes[v] }) .filter(function(v, i, a) { return ((i === 0) ? v !== codes[f] : v !== a[i - 1]); }) .join(''); return (r + '000').slice(0, 4).toUpperCase(); } ```