MCPcopy Create free account
hub / github.com/careercup/CtCI-6th-Edition-JavaScript / palinPerm

Function palinPerm

chapter01/1.4 - PalinPerm/palinPerm.js:1–30  ·  view source on GitHub ↗
(string)

Source from the content-addressed store, hash-verified

1var 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
33console.log(palinPerm('Tact Coa'), 'true');

Callers 1

palinPerm.jsFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected