(str1, str2)
| 39 | * @example - checkAnagramMap('Eleven plus two', 'Twelve plus one') => true |
| 40 | */ |
| 41 | const 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 | |
| 75 | export { checkAnagramRegex, checkAnagramMap } |
no test coverage detected