* Parses a human-readable size string into a byte count. * @param {number | string} size - A number (floored to an integer), a numeric string * (treated as bytes), or a string with a unit suffix: `b`, `kb`, `mb`, `gb` * (case-insensitive). Examples: `'20mb'`, `'512kb'`, `'1.5gb'`, `1048
(size)
| 552 | * @throws {Error} If the string does not match the expected format. |
| 553 | */ |
| 554 | static parseSizeToBytes(size) { |
| 555 | if (typeof size === 'number') { |
| 556 | if (!Number.isFinite(size) || size < 0) { |
| 557 | throw new Error(`Invalid size value: ${size}`); |
| 558 | } |
| 559 | return Math.floor(size); |
| 560 | } |
| 561 | const str = String(size).trim().toLowerCase(); |
| 562 | const match = str.match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/); |
| 563 | if (!match) { |
| 564 | throw new Error(`Invalid size value: ${size}`); |
| 565 | } |
| 566 | const num = parseFloat(match[1]); |
| 567 | const unit = match[2]; |
| 568 | switch (unit) { |
| 569 | case 'kb': |
| 570 | return Math.floor(num * 1024); |
| 571 | case 'mb': |
| 572 | return Math.floor(num * 1024 * 1024); |
| 573 | case 'gb': |
| 574 | return Math.floor(num * 1024 * 1024 * 1024); |
| 575 | default: |
| 576 | return Math.floor(num); |
| 577 | } |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | module.exports = Utils; |
no test coverage detected