* Converts a string representing an amount of memory to bytes. * * @param input The value to convert to bytes. * @param percentageReference The reference value to use when a '%' value is supplied.
( input: string | number | null | undefined, percentageReference?: number, )
| 22 | * @param percentageReference The reference value to use when a '%' value is supplied. |
| 23 | */ |
| 24 | function stringToBytes( |
| 25 | input: string | number | null | undefined, |
| 26 | percentageReference?: number, |
| 27 | ): number | null | undefined { |
| 28 | if (input === null || input === undefined) { |
| 29 | return input; |
| 30 | } |
| 31 | |
| 32 | if (typeof input === 'string') { |
| 33 | if (Number.isNaN(Number.parseFloat(input.slice(-1)))) { |
| 34 | // eslint-disable-next-line prefer-const |
| 35 | let [, numericString, trailingChars] = |
| 36 | input.match(/(.*?)([^\d.-]+)$/i) || []; |
| 37 | |
| 38 | if (trailingChars && numericString) { |
| 39 | const numericValue = Number.parseFloat(numericString); |
| 40 | trailingChars = trailingChars.toLowerCase(); |
| 41 | |
| 42 | switch (trailingChars) { |
| 43 | case '%': |
| 44 | input = numericValue / 100; |
| 45 | break; |
| 46 | case 'kb': |
| 47 | case 'k': |
| 48 | return numericValue * 1000; |
| 49 | case 'kib': |
| 50 | return numericValue * 1024; |
| 51 | case 'mb': |
| 52 | case 'm': |
| 53 | return numericValue * 1000 * 1000; |
| 54 | case 'mib': |
| 55 | return numericValue * 1024 * 1024; |
| 56 | case 'gb': |
| 57 | case 'g': |
| 58 | return numericValue * 1000 * 1000 * 1000; |
| 59 | case 'gib': |
| 60 | return numericValue * 1024 * 1024 * 1024; |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | // It ends in some kind of char so we need to do some parsing |
| 65 | } else { |
| 66 | input = Number.parseFloat(input); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | if (typeof input === 'number') { |
| 71 | if (input === 0) { |
| 72 | return 0; |
| 73 | } else if (input <= 1 && input > 0) { |
| 74 | if (percentageReference) { |
| 75 | return Math.floor(input * percentageReference); |
| 76 | } else { |
| 77 | throw new Error( |
| 78 | 'For a percentage based memory limit a percentageReference must be supplied', |
| 79 | ); |
| 80 | } |
| 81 | } else if (input > 1) { |
no test coverage detected