forked from jestjs/jest
/
stringToBytes.ts
90 lines (81 loc) 路 2.52 KB
/
stringToBytes.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function stringToBytes(
input: undefined,
percentageReference?: number,
): undefined;
function stringToBytes(input: null, percentageReference?: number): null;
function stringToBytes(
input: string | number,
percentageReference?: number,
): number;
/**
* 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.
*/
function stringToBytes(
input: string | number | null | undefined,
percentageReference?: number,
): number | null | undefined {
if (input === null || input === undefined) {
return input;
}
if (typeof input === 'string') {
if (isNaN(Number.parseFloat(input.slice(-1)))) {
// eslint-disable-next-line prefer-const
let [, numericString, trailingChars] =
input.match(/(.*?)([^0-9.-]+)$/i) || [];
if (trailingChars && numericString) {
const numericValue = Number.parseFloat(numericString);
trailingChars = trailingChars.toLowerCase();
switch (trailingChars) {
case '%':
input = numericValue / 100;
break;
case 'kb':
case 'k':
return numericValue * 1000;
case 'kib':
return numericValue * 1024;
case 'mb':
case 'm':
return numericValue * 1000 * 1000;
case 'mib':
return numericValue * 1024 * 1024;
case 'gb':
case 'g':
return numericValue * 1000 * 1000 * 1000;
case 'gib':
return numericValue * 1024 * 1024 * 1024;
}
}
// It ends in some kind of char so we need to do some parsing
} else {
input = Number.parseFloat(input);
}
}
if (typeof input === 'number') {
if (input <= 1 && input > 0) {
if (percentageReference) {
return Math.floor(input * percentageReference);
} else {
throw new Error(
'For a percentage based memory limit a percentageReference must be supplied',
);
}
} else if (input > 1) {
return Math.floor(input);
} else {
throw new Error('Unexpected numerical input');
}
}
throw new Error('Unexpected input');
}
// https://github.com/import-js/eslint-plugin-import/issues/1590
export default stringToBytes;