Anagram v2

Anagram v2


An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Consider capital letters to be the same as lower case


Examples
anagram(‘Dormitory’ , ‘Dirty room’) = true
anagram(‘The earthquakes’ , ‘The queer shakes’) = true
anagram(‘Astronomer’ ,’Moon starrer’) = true
anagram(‘Hello World’ , ‘Bye There’) = false

function anagram(stringA, stringB) {
	return cleaning(stringA) === cleaning(stringB);
}

function cleaning(str) {
	return 
	str.replace(/[^\w]/g, '').toLowerCase().split('').sort().join('');
}

console.log(anagram('Dormitory' , 'Dirty room'))



First we create function anagram with parameters stringA and stringB.

Then we create helper function buildCharMap with parameter str then we create empty object that will serve as our character map we’ll than iterate through our string and for every character inside there will be add it to our character map

One other thing to keep in mind is that we needs our string to be only considering lowercase characters and we also need to strip out any spaces or any punctuation.

Then we loop with for of loop like this for(let char of str.replace(/[^\w]/g, ‘’)).toLowerCase(); This will strip out any spaces or any punctuation and turn into lowercase with chaining the toLowerCase();

Inside the loop we say charMap[char] = charMap[char] + 1 || 1; This means if char is found more than once we increment by 1 or if not we default it with || to 1;

In the end of this helper function buildCharMap we return charMap



Now we go to our main function anagram where we create variable aCharMap = buildCharMap(stringA) and bCharMap = buildCharMap(stringB);

Now we have these character maps and it’s now up to us to compare the two of them together and the other thing we need to still keep in mind is that we need look at the number of keys inside of both these maps and check to see if they are indentical in length. So approach that we are going to go with so we are going to pull out all the keys from both these objects and we’ll count the number of keys that is contained in both.

If you have never pulled out the number of keys inside an object we use Object.keys(object).lenght

So we check with if statement if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length) we return false;



Now if they do have the same number of characters that we want to proceed with the map checking process in which we will loop at each one of the characters and compare the number of uses that it has to the other map.

Now we are going to iterate into aCharMap with for in loop and if(*aCharMap[char] !== *bCharMap[char]) we return false;

The last thing if our cases are not false we return true;

comments powered by Disqus