
interface INumberFormatOptions {
  maxDecimals?: number
}

function makeIntOps (o?: INumberFormatOptions): Intl.NumberFormatOptions {
  const ops: Intl.NumberFormatOptions = { notation: 'compact' }
  if (o?.maxDecimals !== undefined) {
    ops.maximumFractionDigits = o.maxDecimals
  }
  return ops
}

function formatNumber (n: number | undefined, o?: INumberFormatOptions): string {
  if (n === undefined) {
    return ''
  }
  const ops: Intl.NumberFormatOptions = makeIntOps(o)
  return Intl.NumberFormat('en', ops).format(n)
}

function formatNumbers (ns: Array<number | undefined>, o?: INumberFormatOptions): string[] {
  return ns.map(n => formatNumber(n, o))
}

function formatRange (ns: number[], o: INumberFormatOptions): string {
  const min = Math.min.apply(null, ns)
  const max = Math.max.apply(null, ns)
  const ops: Intl.NumberFormatOptions = makeIntOps(o)
  return Intl.NumberFormat('en', ops).formatRange(min, max)
}

export {
  formatNumber,
  formatNumbers,
  formatRange
}
