Skip to content

Commit

Permalink
feat(utils): local method to extract match at given index
Browse files Browse the repository at this point in the history
fix: passing a non-string value threw errors trying to access string prototypes
  • Loading branch information
Michael committed Oct 17, 2022
1 parent bf77ec3 commit 77218a1
Showing 1 changed file with 46 additions and 4 deletions.
50 changes: 46 additions & 4 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ export function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !isArray(value);
}

export function isString(value: unknown): value is string {
return typeof value === "string";
}

export function isEmpty(value: any): boolean {
if (isArray(value)) {
return value.length === 0;
Expand All @@ -55,22 +59,23 @@ export function isEmpty(value: any): boolean {
}

export function capitalize(value: string): string {
value = String(value);
return value.charAt(0).toUpperCase() + value.slice(1);
}

export function uppercase(value: string): string {
return value.toUpperCase();
export function uppercase<T extends string>(value: T): T {
return String(value).toUpperCase() as T;
}

export function lowercase(value: string): string {
return value.toLowerCase();
return String(value).toLowerCase();
}

export function clone<T>(value: T): T {
if (isArray(value)) {
return value.slice() as T;
} else if (isObject(value)) {
return { ...value } as T;
return Object.assign({}, value) as T;
} else {
return value;
}
Expand Down Expand Up @@ -131,3 +136,40 @@ export function forEach<T extends IObject>(
}
}
}

export function extractMatchFromRegExp(
value: string | null,
regexp: RegExp,
group: number = 0,
defaultValue: any = null
): string | null {
if (value) {
const matches = regexp.exec(value);

if (isArray(matches) && !isEmpty(matches)) {
return matches[group];
}
}

return defaultValue;
}

export function startsWithReplacer(
value: string,
search: string,
replace: string
): string {
if (value.startsWith(search)) {
return value.replace(search, replace);
}

return value;
}

export function ensureLeadingSlash(value: string): string {
if (value.startsWith("/")) {
return value;
}

return `/${value}`;
}

0 comments on commit 77218a1

Please sign in to comment.