Last active
August 29, 2015 14:01
-
-
Save jerryvig/a6bad04984b71c965cb0 to your computer and use it in GitHub Desktop.
String.prototype.isAnagram
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.isAnagram = function (testString) { | |
'use strict'; | |
if (typeof testString === 'string' || testString instanceof String) { | |
if (testString.length !== this.length) { | |
return false; | |
} | |
var thisArray = this.split(''), | |
testStringArray = testString.split(''), | |
thisCharCounts = {}, | |
testStringCharCounts = {}, | |
i, | |
character; | |
for (i=0; i<thisArray.length; i++) { | |
if (thisCharCounts[thisArray[i]] === undefined) { | |
thisCharCounts[thisArray[i]] = 0; | |
} | |
thisCharCounts[thisArray[i]]++; | |
if (testStringCharCounts[testStringArray[i]] === undefined) { | |
testStringCharCounts[testStringArray[i]] = 0; | |
} | |
testStringCharCounts[testStringArray[i]]++; | |
} | |
for (character in thisCharCounts) { | |
if (thisCharCounts[character] !== testStringCharCounts[character]) { | |
return false; | |
} | |
} | |
//If you make it here, you can return true. | |
return true; | |
} | |
return false; | |
}; | |
----QUnit test code here------ | |
test('no input passed to isAnagram should return false', function() { | |
var str = new String('abc'); | |
ok(!str.isAnagram(), 'empty input does not return false'); | |
}); | |
test('cba should be an anagram of abc', function () { | |
var abc = new String('abc'); | |
ok(abc.isAnagram('cba'), 'cba should be an anagram of abc'); | |
}); | |
test('abc should be an anagram of itself', function() { | |
var abc = new String('abc'); | |
ok(abc.isAnagram('abc'), 'abc is not an anagram of itself'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment