Skip to content

Commit eead34c

Browse files
committed
Replace object with Map to store frequencies in 1.2 solution
1 parent c6e8a79 commit eead34c

File tree

1 file changed

+19
-21
lines changed

1 file changed

+19
-21
lines changed
Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,34 @@
11
/*Given two strings, write a method to decide
22
if one is apermutation of the other permutation:*/
33

4-
const isPermutation = (str1, str2) =>{
4+
const isPermutation = (str1, str2) => {
55
if (str1.length !== str2.length) {
66
return false;
77
}
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)) {
1212
return false;
1313
}
1414
}
1515
return true;
1616
//******** helper function ******
1717
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+
);
2624
}
27-
}
25+
};
2826

2927
// 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

Comments
 (0)