Skip to content

Instantly share code, notes, and snippets.

@pgoldrbx
Last active February 17, 2016 00:12
Show Gist options
  • Save pgoldrbx/06894c7b62750d5b5232 to your computer and use it in GitHub Desktop.
Save pgoldrbx/06894c7b62750d5b5232 to your computer and use it in GitHub Desktop.
function MyStringClass(str) {
var map = {};
// front-load the work and has the string
for (var i = 0; i < str.length; i++) {
var char = str[i];
map[char] = map[char] || 0;
map[char]++;
}
this.getCount = function (c) {
return map[c] || 0;
};
this.getMost = function () {
var max = 0;
var results = [];
Object.keys(map).forEach(function (c) {
if (map[c] > max) {
max = map[c];
results = [c];
} else if (map[c] === max) {
results.push(c);
}
});
return results;
}
}
var foo = new MyStringClass('racecar');
console.log(foo.count('a')); // => 2
console.log(foo.most()); // => ['a', 'c', 'r'] (non-deterministic order)
@pgoldrbx
Copy link
Author

rewritten in a "classier" way rather than as an obj factory

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