import { ColumnType, DateFormat, FormulaResultType, ITypeOptions, Language, NumberFormat, TimeFormat, } from '../../../types'; import { exhaustiveSwitch } from '../../../typeUtils'; import { arrayToStringDelimiter, stringToArrayDelimiter } from './constants'; import { transformCurrencyToString } from './transformCurrencyToString'; import { transformDatetimeToString } from './transformDatetimeToString'; import { transformNumberToString } from './transformNumberToString'; export const transformFormulaToString = ( value: string | number, typeOptions: ITypeOptions, opts: { locale?: Language } = {} ): string => { const { errorCode, resultType, numberFormat = NumberFormat.DECIMAL, dateFormat = DateFormat.LOCAL, timeFormat = TimeFormat.TWELVE_HOUR, includeTime = false, precision = 1, currencyFormat = '$', } = typeOptions; if (value === undefined || value === '' || errorCode) return ''; switch (resultType) { case FormulaResultType.DATE: { const arrayValue = ( value ? String(value).split(stringToArrayDelimiter) : [] ).filter((item) => !!item); return arrayValue .map((value) => transformDatetimeToString( value, { dateFormat, timeFormat, includeTime, }, opts.locale ) ) .join(arrayToStringDelimiter); } case FormulaResultType.NUMBER: { const stringValue = String(value); const arrayValue = stringValue .split(stringToArrayDelimiter) .map((item) => Number(item)) .filter((item) => isFinite(item)); switch (numberFormat) { case NumberFormat.DECIMAL: case NumberFormat.PERCENTAGE: case NumberFormat.DECIMAL_WITH_COMMAS: return arrayValue .map((value) => transformNumberToString(value, { precision, numberFormat }) ) .join(arrayToStringDelimiter); case NumberFormat.CURRENCY: return arrayValue .map((value) => transformCurrencyToString(value, { precision, currencyFormat }) ) .join(arrayToStringDelimiter); default: return exhaustiveSwitch({ switchValue: numberFormat, returnValue: '', }); } } case FormulaResultType.TEXT: return String(value); default: { return exhaustiveSwitch({ switchValue: resultType, returnValue: String(value) }) } } };