EXERCISE · AlgoCasts
Anagrams
Check to see if two provided strings are anagrams of eachother. One string is an anagram of another if it uses the same characters in the same quantity.
Directions
Check to see if two provided strings are anagrams of eachother. 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') --> Trueanagrams('RAIL! SAFETY!', 'fairy tales') --> Trueanagrams('Hi there', 'Bye there') --> FalseTry it first#
Copy the stub, make the 6 tests pass on your machine, then open the solution. The reveal is remembered per page in this browser.
function anagrams(stringA, stringB) {} module.exports = anagrams;Solution#
function anagrams(stringA, stringB) { return cleanString(stringA) === cleanString(stringB);} function cleanString(str) { return str .replace(/[^\w]/g, '') .toLowerCase() .split('') .sort() .join('');} module.exports = anagrams;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;}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();}); Verbatim from the repo at 30cf7634. Alternate tabs are the commented-out solutions with the leading // removed and nothing else changed. Run the tests locally with npx jest anagrams inside the fork.
See also