Skip to content

Instantly share code, notes, and snippets.

@sudojunior
Last active March 10, 2023 20:42
Show Gist options
  • Save sudojunior/7ed2d16469e47713f4b1761e8b653345 to your computer and use it in GitHub Desktop.
Save sudojunior/7ed2d16469e47713f4b1761e8b653345 to your computer and use it in GitHub Desktop.

count-of

Count array / list occurrences... 😐

const arr = Array.from(
  { length: 10 },
  () => Math.round(Math.random() * 5)
);
countOf(3, arr);

API

countOf(reference, target)

Searchable is a barebones ArrayLike interface that has the methods it needs to forfill its task.

  • This is to permit the use of a string as a native target - ArrayLike<T> would not have permitted this.
  • reference: T - The search term or element.
  • target: Searchable<T> - The entity to search.

Notes

  • This implementation derives from underscore and lodash but focusing on one element as the query focus.
  • Attempts were made to allow it to accept a function, and then build the string search predicate from there... but that fell short rapidly - and it was not worth investing more time into something that is ultimately slower than the best available native solution.

You can find more of my shenanigans projects with TinkerStorm... might be more interesting, ya never know. 🤷‍♂️

interface Searchable<T> {
length: number;
includes(searchElement: T, fromIndex?: number): boolean
indexOf(searchElement: T, fromIndex?: number): number
}
function countOf<T>(reference: T, target: Searchable<T>) {
// failover, no occurances found
if (!target.includes(reference)) {
return 0;
}
let occurrences = 0;
let lastIndex = 0;
function incrementCount(index) {
lastIndex = index + 1;
occurrences++;
}
while (lastIndex < target.length || occurances <= 0) {
const index = target.indexOf(reference, lastIndex);
if (index < 0) break;
incrementCount(index);
}
return occurrences;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment