Skip to content

Implement the anagram problem solution, write tests #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 15, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions 07_anagrams/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// --- Directions
// Check to see if two provided strings are anagrams of each other.
// One string is an anagram of another if it uses the same characters
// in the same quantity. Only consider characters, not spaces
// or punctuation. Consider capital letters to be the same as lower case
// --- Examples
// anagrams('rail safety', 'fairy tales') --> True
// anagrams('RAIL! SAFETY!', 'fairy tales') --> True
// anagrams('Hi there', 'Bye there') --> False

// Solution 1
// function anagrams(stringA, stringB) {
// const aCharMap = buildCharMap(stringA);
// const bCharMap = buildCharMap(stringB);
//
// if(Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
// return false;
// }
// for (let char in aCharMap) {
// if(aCharMap[char] !== bCharMap[char]) {
// return false
// }
// }
// return true;
// }
//
// function buildCharMap(str) {
// const charMap = {};
// for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
// charMap[char] = charMap[char] + 1 || 1;
// }
// return charMap;
// }


// Solution 2
function anagrams(stringA, stringB) {
return cleanStr(stringA) === cleanStr(stringB);
}

function cleanStr(str) {
return str.replace(/[^\w]/g, '')
.toLowerCase()
.split("")
.sort()
.join("");
}
module.exports = anagrams;
27 changes: 27 additions & 0 deletions 07_anagrams/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const anagrams = require('./index.js');

test('anagrams function exists', () => {
expect(typeof anagrams).toEqual('function');
});

test('"hello" is an anagram of "llohe"', () => {
expect(anagrams('hello', 'llohe')).toBeTruthy();
});

test('"Whoa! Hi!" is an anagram of "Hi! Whoa!"', () => {
expect(anagrams('Whoa! Hi!', 'Hi! Whoa!')).toBeTruthy();
});

test('"One One" is not an anagram of "Two two two"', () => {
expect(anagrams('One One', 'Two two two')).toBeFalsy();
});

test('"One one" is not an anagram of "One one c"', () => {
expect(anagrams('One one', 'One one c')).toBeFalsy();
});

test('"A tree, a life, a bench" is not an anagram of "A tree, a fence, a yard"', () => {
expect(
anagrams('A tree, a life, a bench', 'A tree, a fence, a yard')
).toBeFalsy();
});