Skip to content

Commit

Permalink
string.count
Browse files Browse the repository at this point in the history
  • Loading branch information
rhazarian committed Mar 22, 2024
1 parent c8d6bc0 commit 797e3f9
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,4 +156,30 @@ _G.string.isNotBlank = function (string: string): boolean {
return match(string, "^%s*$")[0] == undefined
}

declare global {
namespace string {
/**
* Returns the number of characters matching the given predicate.
*/
function count(string: string, predicate: (char: string) => boolean): number
}

interface String {
/**
* Returns the number of characters matching the given predicate.
*/
count(predicate: (char: string) => boolean): number
}
}

_G.string.count = function (string: string, predicate: (char: string) => boolean): number {
let result = 0
for (const i of $range(1, string.length)) {
if (predicate(sub(string, i, i))) {
++result
}
}
return result
}

export {}

0 comments on commit 797e3f9

Please sign in to comment.