Skip to content

18-6 Anagram - The anagram function fails to test for duplicate values or empty values #13

Description

@bytesunite

https://github.com/bradtraversy/javascript-sandbox/blob/main/18-unit-testing-algorithms/06-anagrams/algo-testing/anagram/anagram.js

The updated file can be found here:
PacktPublishing#3

The anagram function should return false if both words are the same or when one or both strings are empty.
Of course more could be done to remove special characters & numbers to clean the incoming values.

Currently invoking the following returns true but should be false:

anagram("pop", "pop");
anagram("", "");
anagram(" ", " ");

The quick fix could be a conditional and remove whitespace with replaceAll().

 const cleanStr1 = str1.replaceAll(" ", "").toLowerCase();
 const cleanStr2 = str2.replaceAll(" ", "").toLowerCase();
  if ( str1 === str2 ) { return false; }

Or, clean the string of special characters, numbers & whitespace, using a Regular Expression, then compare:

const pattern = /^[^A-Za-z]+/g;
const cleanStr1 = str1.replaceAll(pattern, "").toLowerCase();
const cleanStr2 = str2.replaceAll(pattern, "").toLowerCase();

if (cleanStr1 === cleanStr2) { return false; }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions