| 1 | var palinPerm = function(string) { |
| 2 | // create object literal to store charcount |
| 3 | var chars = {}; |
| 4 | var currChar; |
| 5 | var mulligan = false; |
| 6 | var isPerm = true; |
| 7 | // pump characters in, spaces not counted, all lowercase |
| 8 | string.split('').forEach((char) => { |
| 9 | if (char !== ' ') { |
| 10 | currChar = char.toLowerCase(); |
| 11 | if (chars[currChar] === undefined) { |
| 12 | chars[currChar] = 0; |
| 13 | } |
| 14 | chars[currChar]++; |
| 15 | } |
| 16 | }); |
| 17 | // check that all chars are even count, except for one exception |
| 18 | Object.keys(chars).forEach((char) => { |
| 19 | if (chars[char] % 2 > 0) { |
| 20 | // if more than one exception, return false |
| 21 | if (mulligan) { |
| 22 | isPerm = false; // return in a forEach statment doesn't flow out of function scope |
| 23 | } else { |
| 24 | mulligan = true; |
| 25 | } |
| 26 | } |
| 27 | }); |
| 28 | // if not return true |
| 29 | return isPerm; |
| 30 | }; |
| 31 | |
| 32 | // TESTS |
| 33 | console.log(palinPerm('Tact Coa'), 'true'); |