-
Notifications
You must be signed in to change notification settings - Fork 0
/
anagram.js
55 lines (50 loc) · 1.43 KB
/
anagram.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// --- Directions
// Check to see if two provided strings are anagrams of eachother.
// One string is an anagram of another if it uses the same characters
// in the same quantity. Only consider characters, not spaces
// or punctuation. Consider capital letters to be the same as lower case
// --- Examples
// anagrams('rail safety', 'fairy tales') --> True
// anagrams('RAIL! SAFETY!', 'fairy tales') --> True
// anagrams('Hi there', 'Bye there') --> False
function anagrams(stringA, stringB) {
return str_check(stringA) === str_check(stringB)
}
function str_check(str) {
return str
.replace(/[^\w]/g, '')
.toLowerCase()
.split('')
.sort()
.join('');
}
// str_a_check('rail safety')
anagrams('rail safety', 'fairy tales') // True
anagrams('Hi there', 'Bye there')
anagrams('RAIL! SAFETY!', 'fairy tales')
// function anagrams(stringA, stringB) {
// const aCharMap = buildCharMap(stringA);
// const bCharMap = buildCharMap(stringB);
//
// if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
// return false;
// }
//
// for (let char in aCharMap) {
// if (aCharMap[char] !== bCharMap[char]) {
// return false;
// }
// }
//
// return true;
// }
//
// function buildCharMap(str) {
// const charMap = {};
//
// for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
// charMap[char] = charMap[char] + 1 || 1;
// }
//
// return charMap;
// }