Write a function that takes two strings as arguments and returns true if they are anagrams of each other, and false otherwise. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
For example, the strings "iceman" and "cinema" are anagrams of each other.
Function Signature: function isAnagram(str1, str2)
Input:
Two strings str1 and str2 of length n (1 ≤ n ≤ 10^3) containing only lowercase letters.
Output:
A boolean value true if the two input strings are anagrams of each other, and false otherwise.
Example:
isAnagram('listen', 'silent'); // true
isAnagram('race', 'care'); // true
isAnagram('night', 'thing'); // false
function isAnagram(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
const frequency = {};
for (let i = 0; i < str1.length; i++) {
const char = str1[i];
if (frequency[char]) {
frequency[char]++;
} else {
frequency[char] = 1;
}
}
for (let i = 0; i < str2.length; i++) {
const char = str2[i];
if (!frequency[char]) {
return false;
} else {
frequency[char]--;
}
}
return true;
}
const chai = require("chai");
const assert = chai.assert;
const Test = require("@codewars/test-compat");
describe('isAnagram', () => {
it('should return true for anagrams', () => {
assert.strictEqual(isAnagram('listen', 'silent'), true);
assert.strictEqual(isAnagram('race', 'care'), true);
});
it('should return false for non-anagrams', () => {
assert.strictEqual(isAnagram('night', 'things'), false);
assert.strictEqual(isAnagram('hello', 'world'), false);
});
it('should return false if input strings have different lengths', () => {
assert.strictEqual(isAnagram('abc', 'abcd'), false);
assert.strictEqual(isAnagram('abcd', 'abc'), false);
assert.strictEqual(isAnagram('anagram', 'nag a ram'), false);
});
});