diff --git a/karpenter/src/helpers/parseRam.test.ts b/karpenter/src/helpers/parseRam.test.ts new file mode 100644 index 0000000000..8c9faf8a39 --- /dev/null +++ b/karpenter/src/helpers/parseRam.test.ts @@ -0,0 +1,30 @@ +import { parseRam } from './parseRam'; + +describe('parseRam', () => { + it('returns 0 for missing or unparseable values', () => { + expect(parseRam('')).toBe(0); + expect(parseRam('abc')).toBe(0); + expect(parseRam('1Xi')).toBe(0); + }); + + it('parses decimal quantities', () => { + expect(parseRam('1.5Gi')).toBe(1.5 * 1024 ** 3); + expect(parseRam('1.5G')).toBe(1.5e9); + }); + + it('parses Pi and Ei', () => { + expect(parseRam('2Pi')).toBe(2 * 1024 ** 5); + expect(parseRam('2Ei')).toBe(2 * 1024 ** 6); + }); + + it('treats suffixes without i as decimal multiples', () => { + expect(parseRam('1G')).toBe(1e9); + expect(parseRam('1Gi')).toBe(1024 ** 3); + }); + + it('parses plain byte counts and existing binary units', () => { + expect(parseRam('1000')).toBe(1000); + expect(parseRam('64Gi')).toBe(68719476736); + expect(parseRam('700Mi')).toBe(734003200); + }); +}); diff --git a/karpenter/src/helpers/parseRam.tsx b/karpenter/src/helpers/parseRam.tsx index 4053c17ed5..a54bc63867 100644 --- a/karpenter/src/helpers/parseRam.tsx +++ b/karpenter/src/helpers/parseRam.tsx @@ -1,21 +1,13 @@ +const DECIMAL_UNITS = ['', 'K', 'M', 'G', 'T', 'P', 'E']; + export function parseRam(ramStr: string): number { if (!ramStr) return 0; - const match = ramStr.match(/^(\d+)([KMGT]i?)?$/i); - if (!match) return 0; - const num = parseInt(match[1]); - const unit = match[2]?.toUpperCase(); + const match = `${ramStr}`.trim().match(/^(\d+(?:\.\d+)?)(?:([KMGTPE])(i)?)?$/i); + if (!match) return 0; - const units: Record = { - K: 1024, - KI: 1024, - M: 1024 * 1024, - MI: 1024 * 1024, - G: 1024 * 1024 * 1024, - GI: 1024 * 1024 * 1024, - T: 1024 * 1024 * 1024 * 1024, - TI: 1024 * 1024 * 1024 * 1024, - }; + const num = parseFloat(match[1]); + const exponent = DECIMAL_UNITS.indexOf(match[2]?.toUpperCase() ?? ''); - return num * (units[unit] || 1); + return num * (match[3] ? 1024 : 1000) ** exponent; }