Skip to content

Instantly share code, notes, and snippets.

@laphilosophia
Created December 29, 2022 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laphilosophia/2b7713e88d6388b5ca88879a115d489a to your computer and use it in GitHub Desktop.
Save laphilosophia/2b7713e88d6388b5ca88879a115d489a to your computer and use it in GitHub Desktop.
Simple, yet elegant python like string count
export default function count(
str: string,
{
trim,
strict,
custom,
}: {
trim?: boolean
strict?: boolean
custom?: RegExp
}
): number {
const regex = RegExp
let result = 0
let spaces = regex(/[\s/\t]/gi)
let alphanumeric = regex(
/[~`!@#$₺%^&*¡™£¢∞§¶•ªº–≠«‘“()_+|}{'":;\/?.>,<œ∑´®†¥¨ˆøπåß∂ƒ©˙∆˚¬µ˜∫√≈\{\}\[\]\\\/\s/\t]/gi
)
if (trim) {
str = str.replace(spaces, '')
}
if (strict) {
str = str.replace(alphanumeric, '')
console.info(
'count function only handles alphanumeric characters when strict option is selected'
)
}
if (custom?.source.length) {
if (strict) {
throw new Error(
'count function can not execute custom expression when strict option is selected.'
)
}
if (!(custom instanceof regex)) {
throw new Error('count function custom option must be a Regular Expression!')
}
if (regex(custom).test(str)) {
str = str.replace(custom, '')
}
}
for (let i = 0; i < str.length; i++) {
result = +(i + 1)
}
return result
}
const c = count('Lorem ipsum dolor sit amet.', {
trim: true,
})
console.log(c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment