Skip to content

Commit 3cb4b42

Browse files
Merge pull request #37 from somekindofwallflower/feature/anagrams
Implement the anagram problem solution, write tests
2 parents ba3079c + 947f70c commit 3cb4b42

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

07_anagrams/index.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// --- Directions
2+
// Check to see if two provided strings are anagrams of each other.
3+
// One string is an anagram of another if it uses the same characters
4+
// in the same quantity. Only consider characters, not spaces
5+
// or punctuation. Consider capital letters to be the same as lower case
6+
// --- Examples
7+
// anagrams('rail safety', 'fairy tales') --> True
8+
// anagrams('RAIL! SAFETY!', 'fairy tales') --> True
9+
// anagrams('Hi there', 'Bye there') --> False
10+
11+
// Solution 1
12+
// function anagrams(stringA, stringB) {
13+
// const aCharMap = buildCharMap(stringA);
14+
// const bCharMap = buildCharMap(stringB);
15+
//
16+
// if(Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
17+
// return false;
18+
// }
19+
// for (let char in aCharMap) {
20+
// if(aCharMap[char] !== bCharMap[char]) {
21+
// return false
22+
// }
23+
// }
24+
// return true;
25+
// }
26+
//
27+
// function buildCharMap(str) {
28+
// const charMap = {};
29+
// for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
30+
// charMap[char] = charMap[char] + 1 || 1;
31+
// }
32+
// return charMap;
33+
// }
34+
35+
36+
// Solution 2
37+
function anagrams(stringA, stringB) {
38+
return cleanStr(stringA) === cleanStr(stringB);
39+
}
40+
41+
function cleanStr(str) {
42+
return str.replace(/[^\w]/g, '')
43+
.toLowerCase()
44+
.split("")
45+
.sort()
46+
.join("");
47+
}
48+
module.exports = anagrams;

07_anagrams/test.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const anagrams = require('./index.js');
2+
3+
test('anagrams function exists', () => {
4+
expect(typeof anagrams).toEqual('function');
5+
});
6+
7+
test('"hello" is an anagram of "llohe"', () => {
8+
expect(anagrams('hello', 'llohe')).toBeTruthy();
9+
});
10+
11+
test('"Whoa! Hi!" is an anagram of "Hi! Whoa!"', () => {
12+
expect(anagrams('Whoa! Hi!', 'Hi! Whoa!')).toBeTruthy();
13+
});
14+
15+
test('"One One" is not an anagram of "Two two two"', () => {
16+
expect(anagrams('One One', 'Two two two')).toBeFalsy();
17+
});
18+
19+
test('"One one" is not an anagram of "One one c"', () => {
20+
expect(anagrams('One one', 'One one c')).toBeFalsy();
21+
});
22+
23+
test('"A tree, a life, a bench" is not an anagram of "A tree, a fence, a yard"', () => {
24+
expect(
25+
anagrams('A tree, a life, a bench', 'A tree, a fence, a yard')
26+
).toBeFalsy();
27+
});

0 commit comments

Comments
 (0)