From f3c09828649dee5e4a439539e23eb7a0150178ee Mon Sep 17 00:00:00 2001 From: shashank <47443963+guptashak90@users.noreply.github.com> Date: Tue, 18 Jun 2019 11:54:33 +0530 Subject: [PATCH] Create areAnagrams.js --- src/areAnagrams.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/areAnagrams.js diff --git a/src/areAnagrams.js b/src/areAnagrams.js new file mode 100644 index 0000000..b9445ca --- /dev/null +++ b/src/areAnagrams.js @@ -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; +}