Last active
April 15, 2020 19:39
-
-
Save yantakus/78322b1c84cc5cb61cec8062430fc478 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { compact, isString, isEmpty } from 'lodash' | |
import { Currency } from 'generated' | |
type RangeUnit = { | |
[name: string]: { | |
value: string | |
inputLabel: string | |
viewLabel: string | |
} | |
} | |
type Props = { | |
data: RangeCondition | |
units?: RangeUnit | string | |
formatFn?: Function | |
format?: Intl.DateTimeFormatOptions | Currency | |
defaultValue?: string | |
short?: boolean | |
displayToValue?: boolean | |
} | |
function rangeToString({ | |
data, | |
units = '', | |
formatFn, | |
format, | |
defaultValue = '', | |
short, | |
displayToValue = true, | |
}: Props) { | |
if (!data) return defaultValue | |
const formatValue = val => (formatFn ? formatFn(val, format) : val) | |
const from = data?.from | |
const to = data?.to | |
const unit = data?.unit | |
const isRange = data?.isRange | |
const fromString = short ? '' : 'from ' | |
const toString = short ? ' - ' : ' to ' | |
const hasValues = from || to | |
const fromPrefix = from && isRange ? fromString : '' | |
const fromValue = from ? formatValue(from) : '' | |
const toPrefix = isRange && displayToValue && from && to ? toString : '' | |
const toValue = isRange && displayToValue && to ? formatValue(to) : '' | |
const unitValue = hasValues | |
? isString(units) | |
? units | |
: units?.[unit]?.viewLabel | |
: '' | |
const result = compact([fromPrefix, fromValue, toPrefix, toValue, unitValue]) | |
if (isEmpty(result)) { | |
return defaultValue | |
} else return result?.join('') | |
} | |
export default rangeToString |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment