Get the name of a number, even if it's stupidly big.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Deze repo is gearchiveerd. U kunt bestanden bekijken en het klonen, maar niet pushen of problemen/pull-requests openen.

44 regels
1.4 KiB

  1. import NumberSystem from './NumberSystem'
  2. import ConverterStream from './ConverterStream'
  3. import { ReadStreamOptions, ConvertOptions } from './common'
  4. export default class Converter {
  5. constructor(private readonly system: NumberSystem) {}
  6. convert(value: string | number | bigint, options: ConvertOptions) {
  7. let converted: string[] = []
  8. switch (typeof value!) {
  9. case 'string':
  10. return ''
  11. case 'bigint':
  12. case 'number':
  13. let current = value as number
  14. let thousandPower = 0
  15. while (current > 0) {
  16. const hundreds = Math.floor((current % 1000) / 100)
  17. const tens = Math.floor((current % 100) / 10)
  18. const ones = Math.floor(current % 10)
  19. if (!(ones === 0 && tens === 0 && hundreds === 0)) {
  20. if (thousandPower > 0) {
  21. const { scale = 'short' } = options
  22. converted.unshift(this.system.getKiloName[scale!]!(thousandPower))
  23. }
  24. converted.unshift(this.system.getKiloCount(hundreds, tens, ones))
  25. }
  26. thousandPower = thousandPower + 1
  27. current = Math.floor(current / 1000)
  28. }
  29. return converted.join(' ')
  30. default:
  31. break
  32. }
  33. throw TypeError('Invalid argument passed to value.')
  34. }
  35. readStream(options: ReadStreamOptions): ConverterStream {
  36. const { scale = 'short', encoding = 'utf-8' } = options
  37. return new ConverterStream(this.system, { scale, encoding })
  38. }
  39. }