import { Pipe, PipeTransform } from '@angular/core'

@Pipe({
  name: 'thousandSeparator',
  standalone: false
})
export class ThousandSeparatorPipe implements PipeTransform {
  transform(value: string | number, separator?: string): string {
    return this.addSeparators(value.toString(), separator)
  }

  private addSeparators(value: string, separator: string = ' ') {
    value += ''
    const decimalSplit = value.split('.')
    let whole = decimalSplit[0]
    const fractional = decimalSplit.length > 1 ? '.' + decimalSplit[1] : ''
    const regex = /(\d+)(\d{3})/
    while (regex.test(whole)) {
      whole = whole.replace(regex, '$1' + separator + '$2')
    }
    return whole + fractional
  }
}
