From 815141a04f6b2d5dad4ca5f062cae91774de9cef Mon Sep 17 00:00:00 2001 From: 0721Betty <1942433767@qq.com> Date: Wed, 28 Feb 2024 15:48:50 +0800 Subject: [PATCH] feat(units): add formatValueToMinUnit function --- packages/utils/lib/__test__/format.test.ts | 19 ++++++++++++- packages/utils/lib/format.ts | 33 ++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/packages/utils/lib/__test__/format.test.ts b/packages/utils/lib/__test__/format.test.ts index 62e9d94..cd58510 100644 --- a/packages/utils/lib/__test__/format.test.ts +++ b/packages/utils/lib/__test__/format.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { formatSizeUnit } from '../format.ts' +import { formatSizeUnit, formatValueToMinUnit } from '../format' describe('formatSizeUnit', () => { it('should correctly format bytes', () => { @@ -21,3 +21,20 @@ describe('formatSizeUnit', () => { ) }) }) + +describe('formatValueToMinUnit', () => { + it('should correctly format value with unit', () => { + expect(formatValueToMinUnit(10, 'KB')).toBe(10240) + expect(formatValueToMinUnit(5, 'MB')).toBe(5242880) + expect(formatValueToMinUnit(1, 's')).toBe(1000) + }) + + it('should throw an error for invalid unit', () => { + // @ts-ignore + expect(() => formatValueToMinUnit(10, 'TB')).toThrow('Invalid unit: TB') + // @ts-ignore + expect(() => formatValueToMinUnit(5, 'PB')).toThrow('Invalid unit: PB') + // @ts-ignore + expect(() => formatValueToMinUnit(10, 'S')).toThrow('Invalid unit: S') + }) +}) diff --git a/packages/utils/lib/format.ts b/packages/utils/lib/format.ts index f7e6d68..a3f76d1 100644 --- a/packages/utils/lib/format.ts +++ b/packages/utils/lib/format.ts @@ -16,3 +16,36 @@ export const formatSizeUnit = (val: number) => { const size = (val / 1024 ** index).toFixed(1) return `${size} ${unitArr[index]}` } + +/** + * Converts a given value from one unit to its equivalent in the smallest unit of the same type. + * + * For example, it converts a value in kilobytes (KB) to bytes (B), or a value in hours (h) to milliseconds (ms). + * The smallest unit for time is millisecond (ms), and for size is byte (B). + * + * @param {number} value - The numeric value to be converted. + * @param {string} unit - The unit of the value, which is a key of the SizeOrTimeUnit enum. + * @returns {number} The input value converted to the smallest unit. + * @throws {Error} If the provided unit is not a key in the SizeOrTimeUnit enum. + * + * @example + * // returns 1024, converts 1 kilobyte to bytes + * formatValueToMinUnit(1, 'KB'); + */ +enum SizeOrTimeUnit { + ms = 1, + s = 1000, + m = 1000 * 60, + h = 1000 * 60 * 60, + d = 1000 * 60 * 60 * 24, + B = 1, + KB = 1024, + MB = 1024 * 1024, + GB = 1024 * 1024 * 1024, +} +export const formatValueToMinUnit = (value: number, unit: keyof typeof SizeOrTimeUnit) => { + if (!(unit in SizeOrTimeUnit)) { + throw new Error(`Invalid unit: ${unit}`) + } + return value * SizeOrTimeUnit[unit] +}