All files / utils indent.ts

100% Statements 12/12
100% Branches 4/4
100% Functions 1/1
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                                21x   21x 13x 13x 13x 13x 7x             13x 13x     21x   21x    
/**
 * 每一行紧跟前导空白的插入值为多行时,保持缩进。
 *
 * @public
 * @param literals 字面值
 * @param interpolations 插入值
 * @returns 返回处理后的结果
 * @example
 * ```typescript
 * indent` ${'a\nb'}` // => ' a\n b'
 * ```
 */
export function indent(
  literals: TemplateStringsArray,
  ...interpolations: Array<string | number>
): string {
  let result = ''
 
  for (let i = 0; i < interpolations.length; i++) {
    const literal = literals[i]
    let interpolation = interpolations[i]
    const match = literal.match(/(?:^|[\r\n]+)([^\S\r\n]*)$/)
    if (match && match[1]) {
      interpolation = String(interpolation).replace(
        // fix: 后行断言部分浏览器暂不支持
        // /(?<=[\r\n]+)(?=[^\r\n])/g,
        /([\r\n]+)(?=[^\r\n])/g,
        `$1${match[1]}`,
      )
    }
    result += literal
    result += interpolation
  }
 
  result += literals[literals.length - 1]
 
  return result
}