Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions karpenter/src/helpers/parseRam.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
22 changes: 7 additions & 15 deletions karpenter/src/helpers/parseRam.tsx
Original file line number Diff line number Diff line change
@@ -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<string, number> = {
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;
}