MCPcopy Index your code
hub / github.com/TheAlgorithms/JavaScript / checkAnagramMap

Function checkAnagramMap

String/CheckAnagram.js:41–73  ·  view source on GitHub ↗
(str1, str2)

Source from the content-addressed store, hash-verified

39 * @example - checkAnagramMap('Eleven plus two', 'Twelve plus one') => true
40 */
41const checkAnagramMap = (str1, str2) => {
42 // check that inputs are strings.
43 if (typeof str1 !== 'string' || typeof str2 !== 'string') {
44 throw new TypeError('Both arguments should be strings.')
45 }
46
47 // If both strings have not same lengths then they can not be anagram.
48 if (str1.length !== str2.length) {
49 return false
50 }
51
52 const str1List = Array.from(str1.toUpperCase()) // str1 to array
53
54 // get the occurrences of str1 characters by using HashMap
55 const str1Occurs = str1List.reduce(
56 (map, char) => map.set(char, map.get(char) + 1 || 1),
57 new Map()
58 )
59
60 for (const char of str2.toUpperCase()) {
61 // if char has not exist to the map it's return false
62 if (!str1Occurs.has(char)) {
63 return false
64 }
65
66 let getCharCount = str1Occurs.get(char)
67 str1Occurs.set(char, --getCharCount)
68
69 getCharCount === 0 && str1Occurs.delete(char)
70 }
71
72 return true
73}
74
75export { checkAnagramRegex, checkAnagramMap }

Callers 1

Calls 4

setMethod · 0.45
getMethod · 0.45
hasMethod · 0.45
deleteMethod · 0.45

Tested by

no test coverage detected