Skip to content
This repository was archived by the owner on Aug 26, 2019. It is now read-only.
Open
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
27 changes: 27 additions & 0 deletions src/areAnagrams.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
export const areAnagram = (word1, word2) => {
if (typeof word1 !== 'string' || typeof word2 !== 'string') {
throw new Error('This requires two strings to be passed.')
}

var normalizedWord1 = word1.replace(/[^A-Za-z]+/g, '').toLowerCase();
var normalizedWord2 = word2.replace(/[^A-Za-z]+/g, '').toLowerCase();

var counts = [];
var word1Length = normalizedWord1.length;
var word2Length = normalizedWord2.length

if (word1Length !== word2Length) { return false; }

for (var i = 0; i < word1Length; i++) {
var index = normalizedWord1.charCodeAt(i)-97;
counts[index] = (counts[index] || 0) + 1;
}

for (var i = 0; i < word2Length; i++) {
var index = normalizedWord2.charCodeAt(i)-97;
if (!counts[index]) { return false; }
else { counts[index]--; }
}

return true;
}