Created
December 29, 2022 16:14
-
-
Save laphilosophia/2b7713e88d6388b5ca88879a115d489a to your computer and use it in GitHub Desktop.
Simple, yet elegant python like string count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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