UNPKG

@yamada-ui/react

Version:

React UI components of the Yamada, by the Yamada, for the Yamada built with React and Emotion

53 lines (49 loc) 1.51 kB
"use client"; import { useI18n } from "../../providers/i18n-provider/i18n-provider.js"; import { useNumberFormat } from "./use-format-number.js"; import { useCallback } from "react"; //#region src/components/format/use-format-byte.ts const bitPrefixes = [ "", "kilo", "mega", "giga", "tera" ]; const bytePrefixes = [ "", "kilo", "mega", "giga", "tera", "peta" ]; /** * `useFormatByte` is a custom hook that returns the formatted byte. * * @see https://yamada-ui.com/docs/hooks/use-format-byte */ const useFormatByte = (bytes, options) => { return useByteFormat(options)(bytes); }; const useByteFormat = ({ locale, unit: defaultUnit = "byte", unitDisplay: defaultUnitDisplay = "short" } = {}) => { const { locale: defaultLocale } = useI18n(); const numberFormat = useNumberFormat({ locale: locale ?? defaultLocale }); return useCallback((bytes, { unit = defaultUnit, unitDisplay = defaultUnitDisplay } = {}) => { const sanitizedBytes = Number.isNaN(bytes) ? 0 : bytes; const prefix = unit === "bit" ? bitPrefixes : bytePrefixes; const index = Math.max(0, Math.min(Math.floor(Math.log10(sanitizedBytes) / 3), prefix.length - 1)); return numberFormat(sanitizedBytes === 0 ? 0 : Number.parseFloat((sanitizedBytes / 10 ** (3 * index)).toPrecision(3)), { style: "unit", unit: prefix[index] + unit, unitDisplay }); }, [ defaultUnit, defaultUnitDisplay, numberFormat ]); }; //#endregion export { useByteFormat, useFormatByte }; //# sourceMappingURL=use-format-byte.js.map