All files / src interpolate.ts

87.09% Statements 27/31
75% Branches 12/16
100% Functions 3/3
86.2% Lines 25/29

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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65  22x                   1816x     1816x     1816x 1816x 2025x       1816x     1816x     1816x 1816x               22x 406x     406x     406x     406x 406x   406x 1816x 1816x   406x 406x 705x 705x   406x     406x  
import type S from './sanitised.js'
import indentTail from './indent-tail.js'
 
type Margin = {
  column: number,
  open: boolean
}
 
function updateMargin(mutableMargin: Margin, value: string) {
 
  // Locate start of last line.
  const start = value.lastIndexOf('\n') + 1
 
  // New value has multiple lines.
  const multiline = start > 0
 
  // Span of margin on the last line.
  let end = start
  while (end < value.length && value[end] === ' ') {
    end++
  }
 
  // Margin's column.
  const column = end - start
 
  // Last line is full of blanks.
  const blanks = end === value.length
 
  // Update margin.
  mutableMargin.column = multiline ? column : mutableMargin.column + (mutableMargin.open ? column : 0)
  mutableMargin.open = (mutableMargin.open || multiline) && blanks
}
 
/**
 * @returns interpolated array `xs` with values from `ys`; empty array if both arrays are empty.
 * @throws if `xs.length - 1 !== ys.length`
 */
export const interpolate =
  (xs: TemplateStringsArray, ys: S[]): string[] => {
    Iif (!Array.isArray(xs) || !Array.isArray(ys)) {
      throw new TypeError(`Expected xs and ys to be an array, got ${xs} and ${ys}.`)
    }
    Iif ((xs.length === 0) && (ys.length === 0)) {
      return []
    }
    Iif (xs.length - 1 !== ys.length) {
      throw new TypeError(`Expected xs and ys length to be correct, got ${xs.length} and ${ys.length}.`)
    }
    const margin = { column: 0, open: true }
    const rs: string[] = []
    const push =
      (value: string) => {
        rs.push(value)
        updateMargin(margin, value)
      }
    push(xs[0])
    for (let i = 0; i < ys.length; i++) {
      push(indentTail(ys[i].toString(), ' '.repeat(margin.column)))
      push(xs[i + 1])
    }
    return rs
  }
 
export default interpolate