All files / src demargin.ts

88% Statements 22/25
77.77% Branches 7/9
100% Functions 4/4
85.71% Lines 18/21

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 3422x       22x 421x     421x 421x 81x   683x 66x   421x 421x 6910x 65027x 6909x 6909x       421x     421x 6910x       421x  
import isString from './is-string.js'
 
/** @internal */
export const demargin =
  (value: string): string => {
    Iif (!isString(value)) {
      throw new TypeError(`Expected value to be string, got ${value}.`)
    }
    const lines = value.split('\n')
    if ((lines.length > 0) && lines[0].split('').every(_ => _ === ' ')) {
      lines.shift()
    }
    if ((lines.length > 0) && lines[lines.length - 1].split('').every(_ => _ === ' ')) {
      lines.pop()
    }
    let margin = Infinity
    for (const line of lines) {
      for (let i = 0; i < line.length; i++) {
        if (line[i] !== ' ') {
          margin = Math.min(margin, i)
          break
        }
      }
    }
    Iif (margin === Infinity) {
      return lines.join('\n')
    }
    return lines
      .map(_ => _.slice(margin))
      .join('\n')
  }
 
export default demargin