Skip to content

Commit 629a3c2

Browse files
author
Connor Leech
committed
add anagrams
1 parent 8950579 commit 629a3c2

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// --- Directions
2+
// Check to see if two provided strings are anagrams of eachother.
3+
// One string is an anagram of another if it uses the same characters
4+
// in the same quantity. Only consider characters, not spaces
5+
// or punctuation. Consider capital letters to be the same as lower case
6+
// --- Examples
7+
// anagrams('rail safety', 'fairy tales') --> True
8+
// anagrams('RAIL! SAFETY!', 'fairy tales') --> True
9+
// anagrams('Hi there', 'Bye there') --> False
10+
11+
function anagrams(string1, string2){
12+
let sorted1 = string1.replace(/[^\w]/g, '').toLowerCase().split('').sort().join('');
13+
let sorted2 = string2.replace(/[^\w]/g, '').toLowerCase().split('').sort().join('');
14+
15+
return (sorted1 === sorted2);
16+
17+
}
18+
19+
// console.log(anagrams('rail safety', 'fairy tales')); // true
20+
// console.log(anagrams('RAIL! SAFETY!', 'fairy tales')); // true
21+
// console.log(anagrams('Hi there', 'Bye there')); // false
22+
23+
// Regular Expressions:
24+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
25+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
26+
// string.replace(/[^\w]/g, "") --> removes any non-alphanumeric characters
27+
28+
// Object.keys(obj).length --> gets the number of keys in a JS object
29+
30+
31+
function anagramsSolution1(string1, string2){
32+
let obj1 = {},
33+
obj2 = {},
34+
s1 = string1.replace(/[^\w]/g, '').toLowerCase().split('');
35+
s2 = string2.replace(/[^\w]/g, '').toLowerCase().split('');
36+
37+
if(s1.length !== s2.length) return false;
38+
39+
s1.forEach((letter)=>{
40+
obj1[letter] = (obj1[letter]) ? obj1[letter] + 1 : 1;
41+
});
42+
43+
s2.forEach((letter)=>{
44+
obj2[letter] = (obj2[letter]) ? obj2[letter] + 1 : 1;
45+
});
46+
47+
for(var char in obj1){
48+
if(obj1[char] !== obj2[char]) return false;
49+
}
50+
51+
return true;
52+
}
53+
54+
55+
56+
console.log(anagramsSolution1('rail safety', 'fairy tales')); //True
57+
console.log(anagramsSolution1('RAIL! SAFETY!', 'fairy tales')); // True
58+
console.log(anagramsSolution1('Hi there', 'Bye there')); // False
59+
60+
61+
62+
63+
64+
65+
66+
67+
68+
69+
70+
71+
72+
73+
74+
75+
76+
77+
78+
79+
80+

0 commit comments

Comments
 (0)