/javascript/anagram/anagram.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var Anagram = function(matchWord) {

  matchWord = matchWord.toLowerCase();

  // Return the letters of w as an alphabetically sorted string
  var getLetters = function(w) {
    return w.split('').sort().join('');
  };
  var matchLetters = getLetters(matchWord);

  // Determine whether given word is an anagram of the original
  var isAnagram = function(word) {
    word = word.toLowerCase();
    return (word != matchWord && 
            getLetters(word) == matchLetters);
  };


  return {
    matches: function(words) {
      // Allow multiple strings to be passed in as arguments
      if (typeof words == 'string') {
        words = Array.prototype.slice.call(arguments);
      }

      return words.filter(isAnagram);
    }
  };
};

module.exports = Anagram;

@AkA84 thinks this looks great

Comments

I haven't though of sorting the words alphabetically, that's such a simple and effective solution! I stole your idea to add a new iteration of my take on the problem :D

AkA84 commented 13 January 2015 at 18:41 UTC

You're not logged in right now. Please login via GitHub to comment