Skip to content

Instantly share code, notes, and snippets.

@sarkistlt
Last active March 31, 2016 21:19
Show Gist options
  • Save sarkistlt/d3d39bd15f72391e1d558aabea778506 to your computer and use it in GitHub Desktop.
Save sarkistlt/d3d39bd15f72391e1d558aabea778506 to your computer and use it in GitHub Desktop.
String comparison to the number of matching symbols.
let isAnagram = (str1, str2) => {
if (str1.length !== str2.length) return console.log('false');
let obj1 = {},
obj2 = {},
equal = str1.length;
for (let i = 0; i < str1.length; i++) {
(obj1[str1.charAt(i)]) ? obj1[str1.charAt(i)] += 1 : obj1[str1.charAt(i)] = 1;
(obj2[str2.charAt(i)]) ? obj2[str2.charAt(i)] += 1 : obj2[str2.charAt(i)] = 1;
}
for (let key in obj1) {
if (key in obj2 && obj1[key] === obj2[key]) equal -= 1;
}
(equal == 1) ? console.log('true') : console.log('false');
};
isAnagram('aab', 'bba'); // false
isAnagram('aab', 'aba') // true
isAnagram('aab', 'aab') // true
isAnagram('aab', 'aaba') // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment