Skip to content

Instantly share code, notes, and snippets.

@ChathuraGH
Created December 1, 2023 00:42
Show Gist options
  • Save ChathuraGH/dc126bd54b013a1eff7f780a5ae2f746 to your computer and use it in GitHub Desktop.
Save ChathuraGH/dc126bd54b013a1eff7f780a5ae2f746 to your computer and use it in GitHub Desktop.
Character Occurrences Counter of a string
function withAMap(str) {
// A map for the character=>count mappings
const counts = new Map();
// Loop through the string...
for (const ch of str) {
// Get the count for it, if we have one; we'll get `undefined` if we don't
// know this character yet. Using nullish coalescing (`??`), we can turn
// that `undefined` into a `0`. (In obsolete environments that don't
// support nullish coalescing, for this use case we could use the logical
// OR operator [`||`] instead to use `0` instead of any falsy value, since
// A) `undefined` is falsy, and B) None of the count values we're tracking
// will be falsy because they're all non-zero. For some other use cases,
// we'd need to use a conditional testing `undefined` explicitly.)
const count = counts.get(ch) ?? 0;
// Add one and store the result
counts.set(ch, count + 1);
}
// Show the counts
for (const [ch, count] of counts) {
console.log(`"${ch}" count: ${counts.get(ch)}`);
}
}
function withAnObject(str) {
// An object for the character=>count mappings
// We use `Object.create(null)` so the object doesn't have any inherited properties
const counts = Object.create(null);
// Loop through the string...
for (const ch of str) {
// Get the count for it, if we have one; we'll get `undefined` if we don't
// know this character yet. Using nullish coalescing (`??`), we can turn
// that `undefined` into a `0`. (In obsolete environments that don't
// support nullish coalescing, for this use case we could use the logical
// OR operator [`||`] instead to use `0` instead of any falsy value, since
// A) `undefined` is falsy, and B) None of the count values we're tracking
// will be falsy because they're all non-zero. For some other use cases,
// we'd need to use a conditional testing `undefined` explicitly.)
const count = counts[ch] ?? 0;
// Add one and store the result
counts[ch] = count + 1;
}
// Show the counts
for (const ch in counts) {
console.log(`"${ch}" count: ${counts[ch]}`);
}
}
const str = "abc321";
console.log("With a Map:");
withAMap(str);
console.log("With an object:");
withAnObject(str);
//source
//https://stackoverflow.com/questions/19480916/count-number-of-occurrences-for-each-char-in-a-string
//https://stackoverflow.com/a/19480979/13861187
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment