UNPKG

apphouse

Version:

Component library for React that uses observable state management and theme-able components.

41 lines (36 loc) 1 kB
import { Unit } from '../../types/unit'; /** * Get value with with equivalent unit * @param value * @param unit * @returns string * * @example * console.log(getValueWithUnit(10, 'px')); // Output: "10px" * console.log(getValueWithUnit(20, 'pt')); // Output: "26.6pt" (20 * 1.33) * console.log(getValueWithUnit(15, 'sp')); // Output: "22.5sp" (15 * 1.5) * console.log(getValueWithUnit(2, 'rem')); // Output: "32rem" (2 * 16) */ export const getValueWithUnit = ( value: number | string, unit: Unit ): string => { const unitConversions = { px: 1, pt: 1.33, sp: 1.5, rem: 16 }; if (typeof value === 'string') { const parsedValue = parseFloat(value); if (isNaN(parsedValue)) { throw new Error(`Invalid value: ${value}`); } value = parsedValue; } if (typeof value !== 'number') { throw new Error(`Invalid value type: ${typeof value}`); } const convertedValue = value * unitConversions[unit]; return `${convertedValue}${unit}`; };