Let's take the example interview question: given a string, how do you determine if it is an anagram of a palindrome? The answer is that, for any given character, at most 1 should appear in the string an odd number of times. Here is an implementation in Scala, with higher-order functions:
def isAnagramOfPalindrome(s: String): Boolean =
s.groupBy { c => c }
.map { case(key, value) => value.size() }
.filter { n => n % 2 != 0 }
.size <= 1
And here's a more traditional implementation in JavaScript. function isAnagramOfPalindrome(str) {
var chars = {};
for (var i = 0; i < str.length; i++) {
var char = str.charAt(i);
chars[char] = (chars[char] || 0) + 1;
}
var numOdd = 0;
for (var key in chars) {
if (chars[key] % 2 != 0) numOdd++;
}
return numOdd <= 1;
}
I find the Scala version much more readable, but I'm assuming you'll prefer the JS version?