-
Code const areAnagrams = (word1, word2) => { const clean = str => str.replace(/\s/g, '').toLowerCase(); const count = str => Array.from(clean(str)).reduce((map, char) => map.set(char, (map.get(char) || 0) + 1), new Map()); const map1 = count(word1); const map2 = count(word2); return Array.from(map1.keys()).every(char => map1.get(char) === map2.get(char)); };
Test Cases // Since Node 10, we're using Mocha. // You can use `chai` for assertions. const chai = require("chai"); const assert = chai.assert; const Test = require('@codewars/test-compat'); // Uncomment the following line to disable truncating failure messages for deep equals, do: // chai.config.truncateThreshold = 0; // Since Node 12, we no longer include assertions from our deprecated custom test framework by default. // Uncomment the following to use the old assertions: // const Test = require("@codewars/test-compat"); describe("Anagram Detector", function () { it("should return true for anagrams", function () { Test.assertEquals(areAnagrams("listen", "silent"), true); Test.assertEquals(areAnagrams("Dormitory", "dirty room"), true); Test.assertEquals(areAnagrams("The Morse Code", "Here come dots"), true); Test.assertEquals(areAnagrams("Astronomer", "Moon starer"), true); }); it("should return false for non-anagrams", function () { Test.assertEquals(areAnagrams("hello", "world"), false); Test.assertEquals(areAnagrams("abc", "def"), false); }); it("should handle spaces and case insensitivity", function () { Test.assertEquals(areAnagrams("Astronomer", "moon starer"), true); }); });
Output:
-
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}