diff --git a/07_anagrams/index.js b/07_anagrams/index.js new file mode 100644 index 0000000..cf4875d --- /dev/null +++ b/07_anagrams/index.js @@ -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; diff --git a/07_anagrams/test.js b/07_anagrams/test.js new file mode 100644 index 0000000..dddeb79 --- /dev/null +++ b/07_anagrams/test.js @@ -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(); +});