All files / regexp RegExpBuilder.ts

100% Statements 11/11
100% Branches 8/8
100% Functions 3/3
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40                                    2x       207x 207x 10x   207x 128x     207x 207x 57x     207x 207x      
export interface RegExpBuilderOptions {
  /** 基础正则表达式 */
  baseRegExp: RegExp
}
 
export interface RegExpBuilderBuildOptions {
  /** `g` */
  global?: boolean
  /** `^...$` */
  exact?: boolean
  /** `...+` */
  repeat?: boolean
}
 
export class RegExpBuilder {
  constructor(private options: RegExpBuilderOptions) {}
 
  getBaseRegExp(): RegExp {
    return new RegExp(this.options.baseRegExp)
  }
 
  build(options?: RegExpBuilderBuildOptions): RegExp {
    let regExpSource = `(?:${this.options.baseRegExp.source})`
    if (options?.repeat) {
      regExpSource = `${regExpSource}+`
    }
    if (options?.exact) {
      regExpSource = `^${regExpSource}$`
    }
 
    let regExpFlags = this.options.baseRegExp.flags
    if (options?.global && this.options.baseRegExp.flags.indexOf('g') === -1) {
      regExpFlags = `${regExpFlags}g`
    }
 
    const regExp = new RegExp(regExpSource, regExpFlags)
    return regExp
  }
}