|
1 | 1 | /*Given two strings, write a method to decide
|
2 | 2 | if one is apermutation of the other permutation:*/
|
3 | 3 |
|
4 |
| -const isPermutation = (str1, str2) =>{ |
| 4 | +const isPermutation = (str1, str2) => { |
5 | 5 | if (str1.length !== str2.length) {
|
6 | 6 | return false;
|
7 | 7 | }
|
8 |
| - const obj1 = determineCharCount(str1); |
9 |
| - const obj2 = determineCharCount(str2); |
10 |
| - for (let char of str1) { |
11 |
| - if (obj1[char] !== obj2[char]) { |
| 8 | + const freq1 = determineCharCount(str1); |
| 9 | + const freq2 = determineCharCount(str2); |
| 10 | + for (const [char, count] of freq1) { |
| 11 | + if (count !== freq2.get(char)) { |
12 | 12 | return false;
|
13 | 13 | }
|
14 | 14 | }
|
15 | 15 | return true;
|
16 | 16 | //******** helper function ******
|
17 | 17 | function determineCharCount(string) {
|
18 |
| - return string.split('').reduce((acc, char) => { |
19 |
| - if (acc[char] !== undefined) { |
20 |
| - acc[char]++; |
21 |
| - } else { |
22 |
| - acc[char] = 1; |
23 |
| - } |
24 |
| - return acc; |
25 |
| - }, {}); |
| 18 | + return string |
| 19 | + .split('') |
| 20 | + .reduce( |
| 21 | + (acc, char) => acc.set(char, (acc.get(char) || 0) + 1), |
| 22 | + new Map() |
| 23 | + ); |
26 | 24 | }
|
27 |
| -} |
| 25 | +}; |
28 | 26 |
|
29 | 27 | // Tests:
|
30 |
| - console.log(isPermutation('abc', 'abb') === false); |
31 |
| - console.log(isPermutation('abb', 'abc') === false); |
32 |
| - console.log(isPermutation('aaa', 'abc') === false); |
33 |
| - console.log(isPermutation('abc', 'abcd') === false); |
34 |
| - console.log(isPermutation('abc', 'bac') === true); |
35 |
| - console.log(isPermutation('', '') === true); |
36 |
| - console.log(isPermutation('12', '21') === true); |
| 28 | +console.log(isPermutation('abc', 'abb') === false); |
| 29 | +console.log(isPermutation('abb', 'abc') === false); |
| 30 | +console.log(isPermutation('aaa', 'abc') === false); |
| 31 | +console.log(isPermutation('abc', 'abcd') === false); |
| 32 | +console.log(isPermutation('abc', 'bac') === true); |
| 33 | +console.log(isPermutation('', '') === true); |
| 34 | +console.log(isPermutation('12', '21') === true); |
0 commit comments