Skip to content

Commit

Permalink
Reuse replacer function
Browse files Browse the repository at this point in the history
  • Loading branch information
blakeembrey committed May 23, 2024
1 parent 425266f commit c6d683e
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -561,24 +561,20 @@ function escape(str: string) {
}

/**
* Escape and repeat a string for regular expressions.
* Escape and repeat loose characters for regular expressions.
*/
function repeat(str: string) {
return `${escape(str)}+`;
function looseReplacer(value: string, loose: string) {
return loose ? `${escape(value)}+` : escape(value);
}

/**
* Encode all non-delimiter characters using the encode function.
*/
function toStringify(loose: string) {
if (loose) {
const re = new RegExp(`[^${escape(loose)}]+|(.)`, "g");
const replacer = (value: string, loose: string) =>
loose ? repeat(value) : escape(value);
return (value: string) => value.replace(re, replacer);
}
if (!loose) return escape;

return escape;
const re = new RegExp(`[^${escape(loose)}]+|(.)`, "g");
return (value: string) => value.replace(re, looseReplacer);
}

/**
Expand Down

0 comments on commit c6d683e

Please sign in to comment.