Advertisement
Guest User

Untitled

a guest
Sep 20th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. function _countChanger(countsByChar, isIncrement = false) {
  2. const incrementer = (char) => {
  3. if (char === ' ') {
  4. return;
  5. }
  6. var currentCount = countsByChar[char] || 0;
  7. if (isIncrement) {
  8. countsByChar[char] = currentCount + 1;
  9. } else {
  10. countsByChar[char] = currentCount - 1;
  11. }
  12. }
  13. return incrementer;
  14. }
  15.  
  16. // returns: true if the two strings, s1 and s2, are anagrams; false otherwise
  17. function areAnagrams(s1, s2) {
  18. if (!s1 || !s2) {
  19. return false;
  20. }
  21. const countsByChar = {};
  22. s1.split('').forEach(_countChanger(countsByChar, true));
  23. s2.split('').forEach(_countChanger(countsByChar));
  24.  
  25. const counts = Object.values(countsByChar);
  26. return counts.every(num => num === 0);
  27. }
  28.  
  29. console.log('false?: ' + areAnagrams('abc', null));
  30. console.log('false?: ' + areAnagrams(null, 'abc'));
  31. console.log('false?: ' + areAnagrams('anagram', 'not a gram'));
  32. console.log('true?: ' + areAnagrams('ana gram', 'nag a ram'));
  33. console.log('true?: ' + areAnagrams('anagram', 'nag a ram')); // spaces don't matter
  34. console.log('false?: ' + areAnagrams('aa', 'bb'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement