diff --git a/react/src/helper/index.test.tsx b/react/src/helper/index.test.tsx index 2a38048249..8d384a9b12 100644 --- a/react/src/helper/index.test.tsx +++ b/react/src/helper/index.test.tsx @@ -7,6 +7,7 @@ import { isOutsideRangeWithUnits, localeCompare, numberSorterWithInfinityValue, + parseUnit, toFixedFloorWithoutTrailingZeros, transformSorterToOrderString, } from './index'; @@ -82,6 +83,36 @@ describe('iSizeToSize', () => { const result = iSizeToSize(sizeWithUnit); expect(result).toBeUndefined(); }); + + it('should return 0 when input is zero', () => { + const result = iSizeToSize('0g', 'b'); + expect(result?.number).toBe(0); + expect(result?.unit).toBe('B'); + }); +}); + +describe('parseUnit', () => { + test('parses a number with a unit', () => { + expect(parseUnit('123px')).toEqual([123, 'px']); + expect(parseUnit('45.67em')).toEqual([45.67, 'em']); + expect(parseUnit('100%')).toEqual([100, '%']); + }); + + test('parses a number without a unit', () => { + expect(parseUnit('123')).toEqual([123, 'b']); + expect(parseUnit('45.67')).toEqual([45.67, 'b']); + }); + + test('handles invalid input gracefully', () => { + expect(parseUnit('abc')).toEqual([NaN, 'b']); + expect(parseUnit('')).toEqual([NaN, 'b']); + }); + + test('handles edge cases', () => { + expect(parseUnit('0')).toEqual([0, 'b']); + expect(parseUnit('0px')).toEqual([0, 'px']); + expect(parseUnit('.5em')).toEqual([0.5, 'em']); + }); }); describe('compareNumberWithUnits', () => { diff --git a/react/src/helper/index.tsx b/react/src/helper/index.tsx index 6410df1ab4..01899189f3 100644 --- a/react/src/helper/index.tsx +++ b/react/src/helper/index.tsx @@ -278,7 +278,7 @@ export function filterNonNullItems( } export function parseUnit(str: string): [number, string] { - const match = str?.match(/^(\d+(?:\.\d+)?)([a-zA-Z]*)$/); + const match = str?.match(/^(\d*\.?\d+)([a-zA-Z%]*)$/); if (!match) { // If the input doesn't match the pattern, assume it's in bytes return [parseFloat(str), 'b'];