Skip to content

Commit

Permalink
feat(units): add formatValueToMinUnit function
Browse files Browse the repository at this point in the history
  • Loading branch information
0721Betty committed Feb 28, 2024
1 parent 9102b35 commit f955546
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
19 changes: 18 additions & 1 deletion packages/utils/lib/__test__/format.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand All @@ -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')
})
})
33 changes: 33 additions & 0 deletions packages/utils/lib/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]
}

0 comments on commit f955546

Please sign in to comment.