34 lines
1.2 KiB
TypeScript
34 lines
1.2 KiB
TypeScript
export const TRADE_WEIGHT_UNIT_GRAM = 'گرم'
|
|
export const TRADE_WEIGHT_UNIT_KILOGRAM = 'کیلوگرم'
|
|
|
|
export function isKilogramUnit(unit?: string | null) {
|
|
const value = (unit ?? '').trim()
|
|
return value === TRADE_WEIGHT_UNIT_KILOGRAM || value === 'kilogram' || value === 'kg'
|
|
}
|
|
|
|
/** واحد نمایش از ستینگ — خالی یا نامعتبر = گرم */
|
|
export function resolveTradeWeightUnit(settingValue?: string | number | null) {
|
|
return isKilogramUnit(settingValue?.toString()) ? TRADE_WEIGHT_UNIT_KILOGRAM : TRADE_WEIGHT_UNIT_GRAM
|
|
}
|
|
|
|
export function weightToGrams(value: number, fromUnit?: string | null) {
|
|
return isKilogramUnit(fromUnit) ? value * 1000 : value
|
|
}
|
|
|
|
export function gramsToTradeUnit(grams: number, displayUnit?: string | null) {
|
|
return isKilogramUnit(displayUnit ?? resolveTradeWeightUnit(null)) ? grams / 1000 : grams
|
|
}
|
|
|
|
export function convertWeightToDisplayUnit(
|
|
value: number,
|
|
fromUnit?: string | null,
|
|
displayUnit?: string | null
|
|
) {
|
|
return gramsToTradeUnit(weightToGrams(value, fromUnit), displayUnit)
|
|
}
|
|
|
|
export function formatTradeWeight(value: number, displayUnit?: string | null) {
|
|
const unit = resolveTradeWeightUnit(displayUnit)
|
|
return `${value} ${unit}`
|
|
}
|