parent
45682712d5
commit
e61d60e6b0
3 changed files with 76 additions and 0 deletions
@ -0,0 +1,46 @@ |
||||
import { |
||||
DataSizeUnit, |
||||
formatDataSize, |
||||
FormatDataSizeInputValue, |
||||
FormatDataSizeOptions, |
||||
} from 'format-data-size'; |
||||
|
||||
const dsize = ( |
||||
valueToFormat: FormatDataSizeInputValue, |
||||
{ |
||||
fromUnit, |
||||
onFailure, |
||||
onSuccess, |
||||
precision, |
||||
toUnit, |
||||
}: FormatDataSizeOptions & { |
||||
onFailure?: (error?: unknown, value?: string, unit?: DataSizeUnit) => void; |
||||
onSuccess?: { |
||||
bigint?: (value: bigint, unit: DataSizeUnit) => void; |
||||
number?: (value: number, unit: DataSizeUnit) => void; |
||||
string?: (value: string, unit: DataSizeUnit) => void; |
||||
}; |
||||
} = {}, |
||||
): void => { |
||||
const formatted = formatDataSize(valueToFormat, { |
||||
fromUnit, |
||||
precision, |
||||
toUnit, |
||||
}); |
||||
|
||||
if (formatted) { |
||||
const { value, unit } = formatted; |
||||
|
||||
try { |
||||
onSuccess?.bigint?.call(null, BigInt(value), unit); |
||||
onSuccess?.number?.call(null, parseFloat(value), unit); |
||||
onSuccess?.string?.call(null, value, unit); |
||||
} catch (convertValueToTypeError) { |
||||
onFailure?.call(null, convertValueToTypeError, value, unit); |
||||
} |
||||
} else { |
||||
onFailure?.call(null); |
||||
} |
||||
}; |
||||
|
||||
export default dsize; |
@ -0,0 +1,26 @@ |
||||
import { DataSizeUnit, FormatDataSizeInputValue } from 'format-data-size'; |
||||
|
||||
import dsize from './dsize'; |
||||
|
||||
const dsizeToByte = ( |
||||
value: FormatDataSizeInputValue, |
||||
fromUnit: DataSizeUnit, |
||||
onSuccess: (newValue: bigint, unit: DataSizeUnit) => void, |
||||
onFailure?: ( |
||||
error?: unknown, |
||||
unchangedValue?: string, |
||||
unit?: DataSizeUnit, |
||||
) => void, |
||||
): void => { |
||||
dsize(value, { |
||||
fromUnit, |
||||
onFailure, |
||||
onSuccess: { |
||||
bigint: onSuccess, |
||||
}, |
||||
precision: 0, |
||||
toUnit: 'B', |
||||
}); |
||||
}; |
||||
|
||||
export default dsizeToByte; |
@ -0,0 +1,4 @@ |
||||
import dsize from './dsize'; |
||||
import dsizeToByte from './dsizeToByte'; |
||||
|
||||
export { dsize, dsizeToByte }; |
Loading…
Reference in new issue