Skip to content

Commit 8c89a95

Browse files
feat: anagram algorithm
1 parent 0f0d0b0 commit 8c89a95

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

src/algorithms/anagrams/anagrams.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Option 1 ( the hard way )
2+
export const anagrams = (stringA: string, stringB: string) => {
3+
const aCharMap = buildCharMap(stringA);
4+
const bCharMap = buildCharMap(stringB);
5+
6+
if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
7+
return false;
8+
}
9+
10+
for (const char in aCharMap) {
11+
if (aCharMap[char] !== bCharMap[char]) {
12+
return false;
13+
}
14+
}
15+
16+
return true;
17+
};
18+
19+
const buildCharMap = (str: string) => {
20+
const charMap = {};
21+
22+
for (const char of str.replace(/[^\w]/g, '').toLowerCase()) {
23+
charMap[char] = charMap[char] + 1 || 1;
24+
}
25+
26+
return charMap;
27+
};
28+
29+
// Option 2 ( easy way )
30+
export const easyAnagram = (stringA: string, stringB: string) => {
31+
return cleanString(stringA) === cleanString(stringB);
32+
};
33+
34+
const cleanString = str => {
35+
return str.replace(/[^\w]/g, '').toLowerCase().split('').sort().join('');
36+
};
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { anagrams, easyAnagram } from '../anagrams';
2+
import { describe, test } from 'vitest';
3+
4+
describe('Anagrams Algorithm', () => {
5+
test('anagrams function exists', () => {
6+
expect(typeof anagrams).toEqual('function');
7+
expect(typeof easyAnagram).toEqual('function');
8+
});
9+
10+
test('"hello" is an anagram of "llohe"', () => {
11+
expect(anagrams('hello', 'llohe')).toBeTruthy();
12+
expect(easyAnagram('hello', 'llohe')).toBeTruthy();
13+
});
14+
15+
test('"Whoa! Hi!" is an anagram of "Hi! Whoa!"', () => {
16+
expect(anagrams('Whoa! Hi!', 'Hi! Whoa!')).toBeTruthy();
17+
expect(easyAnagram('Whoa! Hi!', 'Hi! Whoa!')).toBeTruthy();
18+
});
19+
20+
test('"One One" is not an anagram of "Two two two"', () => {
21+
expect(anagrams('One One', 'Two two two')).toBeFalsy();
22+
expect(easyAnagram('One One', 'Two two two')).toBeFalsy();
23+
});
24+
25+
test('"One one" is not an anagram of "One one c"', () => {
26+
expect(anagrams('One one', 'One one c')).toBeFalsy();
27+
expect(easyAnagram('One one', 'One one c')).toBeFalsy();
28+
});
29+
30+
test('"A tree, a life, a bench" is not an anagram of "A tree, a fence, a yard"', () => {
31+
expect(
32+
anagrams('A tree, a life, a bench', 'A tree, a fence, a yard'),
33+
).toBeFalsy();
34+
expect(
35+
easyAnagram('A tree, a life, a bench', 'A tree, a fence, a yard'),
36+
).toBeFalsy();
37+
});
38+
});

0 commit comments

Comments
 (0)