text-format.ts 976 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. export type TextDisplayFormat = {
  2. prefix?: string
  3. suffix?: string
  4. emptyText?: string
  5. }
  6. export type TextDeviceFormat = {
  7. decimalPlaces?: number
  8. showUnit?: boolean
  9. }
  10. export const formatTextDisplayValue = (
  11. value: unknown,
  12. { prefix = '', suffix = '', emptyText = '--' }: TextDisplayFormat = {}
  13. ) => {
  14. const text = value === null || value === undefined ? '' : String(value)
  15. if (text === '') {
  16. return emptyText
  17. }
  18. return `${prefix}${text}${suffix}`
  19. }
  20. export const formatTextDeviceValue = (
  21. value: unknown,
  22. unit: string | undefined,
  23. { decimalPlaces = 2, showUnit = true }: TextDeviceFormat = {}
  24. ) => {
  25. if (value === null || value === undefined || value === '') {
  26. return ''
  27. }
  28. const precision = Math.min(Math.max(Math.trunc(decimalPlaces), 0), 6)
  29. const text =
  30. typeof value === 'number' && Number.isFinite(value) ? value.toFixed(precision) : String(value)
  31. if (!showUnit || !unit) {
  32. return text
  33. }
  34. return `${text} ${unit}`
  35. }