Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function _countChanger(countsByChar, isIncrement = false) {
- const incrementer = (char) => {
- if (char === ' ') {
- return;
- }
- var currentCount = countsByChar[char] || 0;
- if (isIncrement) {
- countsByChar[char] = currentCount + 1;
- } else {
- countsByChar[char] = currentCount - 1;
- }
- }
- return incrementer;
- }
- // returns: true if the two strings, s1 and s2, are anagrams; false otherwise
- function areAnagrams(s1, s2) {
- if (!s1 || !s2) {
- return false;
- }
- const countsByChar = {};
- s1.split('').forEach(_countChanger(countsByChar, true));
- s2.split('').forEach(_countChanger(countsByChar));
- const counts = Object.values(countsByChar);
- return counts.every(num => num === 0);
- }
- console.log('false?: ' + areAnagrams('abc', null));
- console.log('false?: ' + areAnagrams(null, 'abc'));
- console.log('false?: ' + areAnagrams('anagram', 'not a gram'));
- console.log('true?: ' + areAnagrams('ana gram', 'nag a ram'));
- console.log('true?: ' + areAnagrams('anagram', 'nag a ram')); // spaces don't matter
- console.log('false?: ' + areAnagrams('aa', 'bb'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement