isAnagramOf method

bool isAnagramOf(
  1. String s
)

Checks whether the String is an anagram of the provided String.

Example

String foo = 'Hello World';
bool isAnagram = foo.isAnagram('World Hello'); // returns true;
String foo = 'Hello World';
bool isAnagram = foo.isAnagram('World Hello!'); // returns false;

Implementation

bool isAnagramOf(String s) {
  if (this.isBlank || s.isBlank) {
    return false;
  }
  final String word1 = this.removeWhiteSpace;

  final String word2 = s.removeWhiteSpace;

  if (word1.length != word2.length) {
    return false;
  }

  Map<String, int> charCount = {};

  word1
      .split('')
      .forEach((char) => charCount[char] = (charCount[char] ?? 0) + 1);

  word2
      .split('')
      .forEach((char) => charCount[char] = (charCount[char] ?? 0) - 1);

  return charCount.values.every((count) => count == 0);
}