@keeex/utils 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +105 -0
  3. package/lib/array.d.ts +28 -0
  4. package/lib/array.js +36 -0
  5. package/lib/arraybuffer.d.ts +138 -0
  6. package/lib/arraybuffer.js +141 -0
  7. package/lib/async/asynctrigger.d.ts +50 -0
  8. package/lib/async/asynctrigger.js +108 -0
  9. package/lib/async/deferredpromise.d.ts +32 -0
  10. package/lib/async/deferredpromise.js +66 -0
  11. package/lib/async/keycache.d.ts +56 -0
  12. package/lib/async/keycache.js +103 -0
  13. package/lib/async/queues.d.ts +69 -0
  14. package/lib/async/queues.js +135 -0
  15. package/lib/async/timecache.d.ts +58 -0
  16. package/lib/async/timecache.js +118 -0
  17. package/lib/base58.d.ts +27 -0
  18. package/lib/base58.js +83 -0
  19. package/lib/base64.d.ts +51 -0
  20. package/lib/base64.js +126 -0
  21. package/lib/benchmark.d.ts +126 -0
  22. package/lib/benchmark.js +177 -0
  23. package/lib/bits/arraybuffer.d.ts +35 -0
  24. package/lib/bits/arraybuffer.js +64 -0
  25. package/lib/bits/base64.d.ts +35 -0
  26. package/lib/bits/base64.js +70 -0
  27. package/lib/bits/hex.d.ts +17 -0
  28. package/lib/bits/hex.js +30 -0
  29. package/lib/bits/uint8array.d.ts +28 -0
  30. package/lib/bits/uint8array.js +42 -0
  31. package/lib/bytebuffer.d.ts +27 -0
  32. package/lib/bytebuffer.js +29 -0
  33. package/lib/consts.d.ts +33 -0
  34. package/lib/consts.js +33 -0
  35. package/lib/cron/logger.d.ts +22 -0
  36. package/lib/cron/logger.js +31 -0
  37. package/lib/cron/scheduledtask.d.ts +71 -0
  38. package/lib/cron/scheduledtask.js +137 -0
  39. package/lib/cron/types.d.ts +53 -0
  40. package/lib/cron/types.js +31 -0
  41. package/lib/cron.d.ts +29 -0
  42. package/lib/cron.js +47 -0
  43. package/lib/dict.d.ts +56 -0
  44. package/lib/dict.js +74 -0
  45. package/lib/error.d.ts +25 -0
  46. package/lib/error.js +41 -0
  47. package/lib/global.d.ts +27 -0
  48. package/lib/global.js +53 -0
  49. package/lib/hex.d.ts +32 -0
  50. package/lib/hex.js +58 -0
  51. package/lib/idx.d.ts +51 -0
  52. package/lib/idx.js +81 -0
  53. package/lib/json.d.ts +57 -0
  54. package/lib/json.js +116 -0
  55. package/lib/marshalling/marshaller.d.ts +51 -0
  56. package/lib/marshalling/marshaller.js +155 -0
  57. package/lib/marshalling/unmarshaller.d.ts +53 -0
  58. package/lib/marshalling/unmarshaller.js +124 -0
  59. package/lib/marshalling/util.d.ts +25 -0
  60. package/lib/marshalling/util.js +25 -0
  61. package/lib/number.d.ts +17 -0
  62. package/lib/number.js +21 -0
  63. package/lib/path.d.ts +25 -0
  64. package/lib/path.js +29 -0
  65. package/lib/promise.d.ts +42 -0
  66. package/lib/promise.js +78 -0
  67. package/lib/starttime.d.ts +23 -0
  68. package/lib/starttime.js +29 -0
  69. package/lib/string.d.ts +65 -0
  70. package/lib/string.js +108 -0
  71. package/lib/types/array.d.ts +34 -0
  72. package/lib/types/array.js +64 -0
  73. package/lib/types/enum.d.ts +30 -0
  74. package/lib/types/enum.js +44 -0
  75. package/lib/types/predicateerror.d.ts +40 -0
  76. package/lib/types/predicateerror.js +107 -0
  77. package/lib/types/primitive.d.ts +23 -0
  78. package/lib/types/primitive.js +34 -0
  79. package/lib/types/record.d.ts +67 -0
  80. package/lib/types/record.js +235 -0
  81. package/lib/types/types.d.ts +64 -0
  82. package/lib/types/types.js +115 -0
  83. package/lib/types/utils.d.ts +18 -0
  84. package/lib/types/utils.js +67 -0
  85. package/lib/uint8array.d.ts +176 -0
  86. package/lib/uint8array.js +438 -0
  87. package/lib/units.d.ts +159 -0
  88. package/lib/units.js +290 -0
  89. package/lib/utils/buffer.d.ts +49 -0
  90. package/lib/utils/buffer.js +79 -0
  91. package/lib/utils/fourbytes.d.ts +29 -0
  92. package/lib/utils/fourbytes.js +45 -0
  93. package/package.json +1 -0
  94. package/web/array.d.ts +28 -0
  95. package/web/array.js +34 -0
  96. package/web/arraybuffer.d.ts +138 -0
  97. package/web/arraybuffer.js +141 -0
  98. package/web/async/asynctrigger.d.ts +50 -0
  99. package/web/async/asynctrigger.js +106 -0
  100. package/web/async/deferredpromise.d.ts +32 -0
  101. package/web/async/deferredpromise.js +65 -0
  102. package/web/async/keycache.d.ts +56 -0
  103. package/web/async/keycache.js +97 -0
  104. package/web/async/queues.d.ts +69 -0
  105. package/web/async/queues.js +131 -0
  106. package/web/async/timecache.d.ts +58 -0
  107. package/web/async/timecache.js +107 -0
  108. package/web/base58.d.ts +27 -0
  109. package/web/base58.js +78 -0
  110. package/web/base64.d.ts +51 -0
  111. package/web/base64.js +136 -0
  112. package/web/benchmark.d.ts +126 -0
  113. package/web/benchmark.js +183 -0
  114. package/web/bits/arraybuffer.d.ts +35 -0
  115. package/web/bits/arraybuffer.js +59 -0
  116. package/web/bits/base64.d.ts +35 -0
  117. package/web/bits/base64.js +67 -0
  118. package/web/bits/hex.d.ts +17 -0
  119. package/web/bits/hex.js +27 -0
  120. package/web/bits/uint8array.d.ts +28 -0
  121. package/web/bits/uint8array.js +41 -0
  122. package/web/bytebuffer.d.ts +27 -0
  123. package/web/bytebuffer.js +29 -0
  124. package/web/consts.d.ts +33 -0
  125. package/web/consts.js +33 -0
  126. package/web/cron/logger.d.ts +22 -0
  127. package/web/cron/logger.js +30 -0
  128. package/web/cron/scheduledtask.d.ts +71 -0
  129. package/web/cron/scheduledtask.js +136 -0
  130. package/web/cron/types.d.ts +53 -0
  131. package/web/cron/types.js +31 -0
  132. package/web/cron.d.ts +29 -0
  133. package/web/cron.js +47 -0
  134. package/web/dict.d.ts +56 -0
  135. package/web/dict.js +67 -0
  136. package/web/error.d.ts +25 -0
  137. package/web/error.js +39 -0
  138. package/web/global.d.ts +27 -0
  139. package/web/global.js +49 -0
  140. package/web/hex.d.ts +32 -0
  141. package/web/hex.js +52 -0
  142. package/web/idx.d.ts +51 -0
  143. package/web/idx.js +76 -0
  144. package/web/json.d.ts +57 -0
  145. package/web/json.js +98 -0
  146. package/web/marshalling/marshaller.d.ts +51 -0
  147. package/web/marshalling/marshaller.js +150 -0
  148. package/web/marshalling/unmarshaller.d.ts +53 -0
  149. package/web/marshalling/unmarshaller.js +115 -0
  150. package/web/marshalling/util.d.ts +25 -0
  151. package/web/marshalling/util.js +25 -0
  152. package/web/number.d.ts +17 -0
  153. package/web/number.js +21 -0
  154. package/web/path.d.ts +25 -0
  155. package/web/path.js +26 -0
  156. package/web/promise.d.ts +42 -0
  157. package/web/promise.js +74 -0
  158. package/web/starttime.d.ts +23 -0
  159. package/web/starttime.js +29 -0
  160. package/web/string.d.ts +65 -0
  161. package/web/string.js +101 -0
  162. package/web/types/array.d.ts +34 -0
  163. package/web/types/array.js +63 -0
  164. package/web/types/enum.d.ts +30 -0
  165. package/web/types/enum.js +40 -0
  166. package/web/types/predicateerror.d.ts +40 -0
  167. package/web/types/predicateerror.js +128 -0
  168. package/web/types/primitive.d.ts +23 -0
  169. package/web/types/primitive.js +33 -0
  170. package/web/types/record.d.ts +67 -0
  171. package/web/types/record.js +213 -0
  172. package/web/types/types.d.ts +64 -0
  173. package/web/types/types.js +123 -0
  174. package/web/types/utils.d.ts +18 -0
  175. package/web/types/utils.js +30 -0
  176. package/web/uint8array.d.ts +176 -0
  177. package/web/uint8array.js +412 -0
  178. package/web/units.d.ts +159 -0
  179. package/web/units.js +312 -0
  180. package/web/utils/buffer.d.ts +49 -0
  181. package/web/utils/buffer.js +76 -0
  182. package/web/utils/fourbytes.d.ts +29 -0
  183. package/web/utils/fourbytes.js +45 -0
package/lib/units.d.ts ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import ms from "ms";
17
+ /** Coerce a delay value to milliseconds using `ms` if a string is provided */
18
+ export declare const delayInMs: (delayInMsValue: number | ms.StringValue) => number;
19
+ /**
20
+ * How to convert from one level to the next for a given unit.
21
+ *
22
+ * @public
23
+ */
24
+ interface UnitConversion {
25
+ prefix?: string;
26
+ unitName?: string;
27
+ suffix?: string;
28
+ multiplierFromPrevious: number;
29
+ }
30
+ /**
31
+ * Description of a unit system to convert from one level to another.
32
+ *
33
+ * @public
34
+ */
35
+ interface UnitDescription {
36
+ prefixUnit?: boolean;
37
+ /** The base name of the unit that will be prefixed/suffixed for each level */
38
+ basename: string;
39
+ /** All conversion levels in order from smallest to largest */
40
+ levels: Array<UnitConversion>;
41
+ }
42
+ /**
43
+ * Convert description for byte based values
44
+ *
45
+ * @public
46
+ */
47
+ export declare const byteUnit: UnitDescription;
48
+ /**
49
+ * Convert description for small time based values
50
+ *
51
+ * Handles `ms`, `s`, `m` (minutes), `h`, `d`, `w` (weeks)
52
+ *
53
+ * @public
54
+ */
55
+ export declare const timeUnit: UnitDescription;
56
+ type InputAllType = string | number | bigint;
57
+ /**
58
+ * Convert a numerical value from a given unit multiplier to another.
59
+ *
60
+ * @param value - Either the value in the base unit multiplier, or a string with a unit
61
+ *
62
+ * @public
63
+ */
64
+ export declare const unitConvert: (unitDescription: UnitDescription, value: string | number, target?: string) => number;
65
+ /**
66
+ * Convert a numerical value from a given unit multiplier to another.
67
+ *
68
+ * This is the bigint variant, and can only handle integer values.
69
+ *
70
+ * @param value - Either the value in the base unit multiplier, or a string with a unit
71
+ *
72
+ * @public
73
+ */
74
+ export declare const unitConvertBigint: (unitDescription: UnitDescription, value: string | bigint | number, target?: string) => bigint;
75
+ /**
76
+ * Display a value in the largest relevant unit.
77
+ *
78
+ * For example, a call with "5678B" would return "5.68kB".
79
+ * This will lose precision and is destined to human reading.
80
+ *
81
+ * @public
82
+ */
83
+ export declare const unitString: (unitDescription: UnitDescription, value: string | number, decimalPlaces?: number) => string;
84
+ /**
85
+ * Display a value in the largest relevant unit.
86
+ *
87
+ * Bigint variant, will not return decimal values.
88
+ *
89
+ * For example, a call with "5678B" would return "5,7kB".
90
+ * This will lose precision and is destined to human reading.
91
+ *
92
+ * @public
93
+ */
94
+ export declare const unitStringBigint: (unitDescription: UnitDescription, value: string | bigint) => string;
95
+ /**
96
+ * Convert a size in bytes from one unit to another.
97
+ *
98
+ * @param targetUnit - Target unit (`kB`, `MB`, etc.). Defaults to `B`.
99
+ *
100
+ * @public
101
+ */
102
+ export declare const byteConvert: (value: string | number, targetUnit?: string) => number;
103
+ /**
104
+ * Convert a size in bytes from one unit to another.
105
+ *
106
+ * Bigint based function; can only handle integer values.
107
+ *
108
+ * @param targetUnit - Target unit (`kB`, `MB`, etc.). Defaults to `B`.
109
+ *
110
+ * @public
111
+ */
112
+ export declare const byteConvertBigint: (value: InputAllType, targetUnit?: string) => bigint;
113
+ /**
114
+ * Display a human-readable byte size value.
115
+ *
116
+ * @public
117
+ */
118
+ export declare const byteString: (value: string | number, decimalPlaces?: number) => string;
119
+ /**
120
+ * Display a human-readable byte size value.
121
+ *
122
+ * Bigint variant, only handle integer values.
123
+ *
124
+ * @public
125
+ */
126
+ export declare const byteStringBigint: (value: string | bigint) => string;
127
+ /**
128
+ * Convert a short time from one unit to another.
129
+ *
130
+ * @param targetUnit - Target unit (`ms`, `h`, etc.). Defaults to `s`.
131
+ *
132
+ * @public
133
+ */
134
+ export declare const timeConvert: (value: string | number, targetUnit?: string) => number;
135
+ /**
136
+ * Convert a short time from one unit to another.
137
+ *
138
+ * Biting based function; can only handle integer values.
139
+ *
140
+ * @param targetUnit - Target unit (`ms`, `h`, etc.). Defaults to `s`.
141
+ *
142
+ * @public
143
+ */
144
+ export declare const timeConvertBigint: (value: InputAllType, targetUnit?: string) => bigint;
145
+ /**
146
+ * Display a human-readable short time value.
147
+ *
148
+ * @public
149
+ */
150
+ export declare const timeString: (value: string | number, decimalPlaces?: number) => string;
151
+ /**
152
+ * Display a human-readable short time value.
153
+ *
154
+ * Bigint variant, only handle integer values.
155
+ *
156
+ * @public
157
+ */
158
+ export declare const timeStringBigint: (value: string | bigint) => string;
159
+ export {};
package/lib/units.js ADDED
@@ -0,0 +1,290 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import ms from "ms";
17
+ import { roundDecimals } from "./number.js";
18
+ /** Coerce a delay value to milliseconds using `ms` if a string is provided */
19
+ export const delayInMs = (delayInMsValue) => {
20
+ if (typeof delayInMsValue === "number")
21
+ return delayInMsValue;
22
+ return ms(delayInMsValue);
23
+ };
24
+ /**
25
+ * Convert description for byte based values
26
+ *
27
+ * @public
28
+ */
29
+ export const byteUnit = {
30
+ basename: "B",
31
+ levels: [
32
+ { multiplierFromPrevious: 1 }, // Base level
33
+ { prefix: "k", multiplierFromPrevious: 1000 },
34
+ { prefix: "M", multiplierFromPrevious: 1000 },
35
+ { prefix: "G", multiplierFromPrevious: 1000 },
36
+ { prefix: "T", multiplierFromPrevious: 1000 },
37
+ { prefix: "P", multiplierFromPrevious: 1000 },
38
+ { prefix: "E", multiplierFromPrevious: 1000 },
39
+ { prefix: "Z", multiplierFromPrevious: 1000 },
40
+ { prefix: "Y", multiplierFromPrevious: 1000 },
41
+ { prefix: "R", multiplierFromPrevious: 1000 },
42
+ { prefix: "Q", multiplierFromPrevious: 1000 },
43
+ ],
44
+ };
45
+ /**
46
+ * Convert description for small time based values
47
+ *
48
+ * Handles `ms`, `s`, `m` (minutes), `h`, `d`, `w` (weeks)
49
+ *
50
+ * @public
51
+ */
52
+ export const timeUnit = {
53
+ basename: "s",
54
+ levels: [
55
+ { unitName: "ms", multiplierFromPrevious: 1 },
56
+ { multiplierFromPrevious: 1000 }, // Base level
57
+ { unitName: "m", multiplierFromPrevious: 60 },
58
+ { unitName: "h", multiplierFromPrevious: 60 },
59
+ { unitName: "d", multiplierFromPrevious: 24 },
60
+ { unitName: "w", multiplierFromPrevious: 7 },
61
+ ],
62
+ };
63
+ /** Return the full name of a level unit */
64
+ const getUnitLevel = (unitDescription, level) => {
65
+ const lvl = unitDescription.levels[level];
66
+ return `${lvl.prefix ?? ""}${lvl.unitName ?? unitDescription.basename}${lvl.suffix ?? ""}`;
67
+ };
68
+ /** Prefix/suffix the numeric value with the requested unit level */
69
+ const addUnitName = (unitDescription, numericValue, levelOrUnit) => {
70
+ const unitStr = typeof levelOrUnit === "string" ? levelOrUnit : getUnitLevel(unitDescription, levelOrUnit);
71
+ if (unitDescription.prefixUnit)
72
+ return `${unitStr}${numericValue}`;
73
+ return `${numericValue}${unitStr}`;
74
+ };
75
+ /** Convert string unit into level in description */
76
+ const convertUnit = (unitDescription, fromUnit, toUnit) => {
77
+ // eslint-disable-next-line @typescript-eslint/init-declarations
78
+ let from;
79
+ // eslint-disable-next-line @typescript-eslint/init-declarations
80
+ let to;
81
+ const fromTrimmed = fromUnit.trim();
82
+ const toTrimmed = toUnit.trim();
83
+ for (let candidateLevel = 0; (from === undefined || to === undefined) && candidateLevel < unitDescription.levels.length; ++candidateLevel) {
84
+ const candidateUnit = getUnitLevel(unitDescription, candidateLevel);
85
+ if (from === undefined && fromTrimmed === candidateUnit)
86
+ from = candidateLevel;
87
+ if (to === undefined && toTrimmed === candidateUnit)
88
+ to = candidateLevel;
89
+ }
90
+ if (from === undefined || to === undefined) {
91
+ throw new Error(`Invalid units ("${fromUnit}", "${toUnit}")`);
92
+ }
93
+ return { from, to };
94
+ };
95
+ const regexBefore = /^(?<unit>[^\d]+)\d+$/u;
96
+ const regexAfter = /^\d+(?<unit>[^\d]+)$/u;
97
+ /** Get the unit text from an input value */
98
+ const getUnitFromValue = (value, unitDesc) => {
99
+ if (typeof value !== "string")
100
+ return unitDesc.basename;
101
+ const regex = unitDesc.prefixUnit ? regexBefore : regexAfter;
102
+ const res = regex.exec(value);
103
+ if (!res?.groups)
104
+ return unitDesc.basename;
105
+ const unit = res.groups.unit;
106
+ return unit.trim();
107
+ };
108
+ const regexValue = /^(?:[^\d]*)(?<value>\d+)(?:[^\d]*)$/u;
109
+ /** Get the numeric value, stripping units */
110
+ const getNumberValue = (value) => {
111
+ if (typeof value === "number")
112
+ return value;
113
+ const res = regexValue.exec(value);
114
+ if (!res?.groups)
115
+ throw new Error(`Missing value (${value})`);
116
+ return parseFloat(res.groups.value);
117
+ };
118
+ /** Get the numeric value, stripping units */
119
+ const getBigintValue = (value) => {
120
+ if (typeof value === "bigint")
121
+ return value;
122
+ if (typeof value === "number")
123
+ return BigInt(value);
124
+ const res = regexValue.exec(value);
125
+ if (!res?.groups)
126
+ throw new Error(`Missing value (${value})`);
127
+ return BigInt(res.groups.value);
128
+ };
129
+ /**
130
+ * Convert a numerical value from a given unit multiplier to another.
131
+ *
132
+ * @param value - Either the value in the base unit multiplier, or a string with a unit
133
+ *
134
+ * @public
135
+ */
136
+ export const unitConvert = (unitDescription, value, target = unitDescription.basename) => {
137
+ const fromUnit = getUnitFromValue(value, unitDescription);
138
+ const levels = convertUnit(unitDescription, fromUnit, target);
139
+ let resValue = getNumberValue(value);
140
+ let currentLevel = levels.from;
141
+ if (levels.from < levels.to) {
142
+ while (currentLevel < levels.to) {
143
+ ++currentLevel;
144
+ resValue /= unitDescription.levels[currentLevel].multiplierFromPrevious;
145
+ }
146
+ }
147
+ else {
148
+ while (currentLevel > levels.to) {
149
+ resValue *= unitDescription.levels[currentLevel].multiplierFromPrevious;
150
+ --currentLevel;
151
+ }
152
+ }
153
+ return resValue;
154
+ };
155
+ /**
156
+ * Convert a numerical value from a given unit multiplier to another.
157
+ *
158
+ * This is the bigint variant, and can only handle integer values.
159
+ *
160
+ * @param value - Either the value in the base unit multiplier, or a string with a unit
161
+ *
162
+ * @public
163
+ */
164
+ export const unitConvertBigint = (unitDescription, value, target = unitDescription.basename) => {
165
+ const fromUnit = getUnitFromValue(value, unitDescription);
166
+ const levels = convertUnit(unitDescription, fromUnit, target);
167
+ let resValue = getBigintValue(value);
168
+ let currentLevel = levels.from;
169
+ if (levels.from < levels.to) {
170
+ while (currentLevel < levels.to) {
171
+ ++currentLevel;
172
+ resValue /= BigInt(unitDescription.levels[currentLevel].multiplierFromPrevious);
173
+ }
174
+ }
175
+ else {
176
+ while (currentLevel > levels.to) {
177
+ resValue *= BigInt(unitDescription.levels[currentLevel].multiplierFromPrevious);
178
+ --currentLevel;
179
+ }
180
+ }
181
+ return resValue;
182
+ };
183
+ /**
184
+ * Display a value in the largest relevant unit.
185
+ *
186
+ * For example, a call with "5678B" would return "5.68kB".
187
+ * This will lose precision and is destined to human reading.
188
+ *
189
+ * @public
190
+ */
191
+ export const unitString = (unitDescription, value, decimalPlaces = 2) => {
192
+ let candidateLevel = 1;
193
+ for (; candidateLevel < unitDescription.levels.length; ++candidateLevel) {
194
+ const unitName = getUnitLevel(unitDescription, candidateLevel);
195
+ const convertedValue = unitConvert(unitDescription, value, unitName);
196
+ if (convertedValue < 1)
197
+ break;
198
+ }
199
+ --candidateLevel;
200
+ const unitName = getUnitLevel(unitDescription, candidateLevel);
201
+ const convertedValue = roundDecimals(unitConvert(unitDescription, value, unitName), decimalPlaces);
202
+ return addUnitName(unitDescription, convertedValue.toString(), unitName);
203
+ };
204
+ /**
205
+ * Display a value in the largest relevant unit.
206
+ *
207
+ * Bigint variant, will not return decimal values.
208
+ *
209
+ * For example, a call with "5678B" would return "5,7kB".
210
+ * This will lose precision and is destined to human reading.
211
+ *
212
+ * @public
213
+ */
214
+ export const unitStringBigint = (unitDescription, value) => {
215
+ let candidateLevel = 1;
216
+ for (; candidateLevel < unitDescription.levels.length; ++candidateLevel) {
217
+ const unitName = getUnitLevel(unitDescription, candidateLevel);
218
+ const convertedValue = unitConvertBigint(unitDescription, value, unitName);
219
+ if (convertedValue < 1)
220
+ break;
221
+ }
222
+ --candidateLevel;
223
+ const unitName = getUnitLevel(unitDescription, candidateLevel);
224
+ const convertedValue = unitConvertBigint(unitDescription, value, unitName);
225
+ return addUnitName(unitDescription, convertedValue.toString(), unitName);
226
+ };
227
+ /**
228
+ * Convert a size in bytes from one unit to another.
229
+ *
230
+ * @param targetUnit - Target unit (`kB`, `MB`, etc.). Defaults to `B`.
231
+ *
232
+ * @public
233
+ */
234
+ export const byteConvert = (value, targetUnit) => unitConvert(byteUnit, value, targetUnit);
235
+ /**
236
+ * Convert a size in bytes from one unit to another.
237
+ *
238
+ * Bigint based function; can only handle integer values.
239
+ *
240
+ * @param targetUnit - Target unit (`kB`, `MB`, etc.). Defaults to `B`.
241
+ *
242
+ * @public
243
+ */
244
+ export const byteConvertBigint = (value, targetUnit) => unitConvertBigint(byteUnit, value, targetUnit);
245
+ /**
246
+ * Display a human-readable byte size value.
247
+ *
248
+ * @public
249
+ */
250
+ export const byteString = (value, decimalPlaces) => unitString(byteUnit, value, decimalPlaces);
251
+ /**
252
+ * Display a human-readable byte size value.
253
+ *
254
+ * Bigint variant, only handle integer values.
255
+ *
256
+ * @public
257
+ */
258
+ export const byteStringBigint = (value) => unitStringBigint(byteUnit, value);
259
+ /**
260
+ * Convert a short time from one unit to another.
261
+ *
262
+ * @param targetUnit - Target unit (`ms`, `h`, etc.). Defaults to `s`.
263
+ *
264
+ * @public
265
+ */
266
+ export const timeConvert = (value, targetUnit) => unitConvert(timeUnit, value, targetUnit);
267
+ /**
268
+ * Convert a short time from one unit to another.
269
+ *
270
+ * Biting based function; can only handle integer values.
271
+ *
272
+ * @param targetUnit - Target unit (`ms`, `h`, etc.). Defaults to `s`.
273
+ *
274
+ * @public
275
+ */
276
+ export const timeConvertBigint = (value, targetUnit) => unitConvertBigint(timeUnit, value, targetUnit);
277
+ /**
278
+ * Display a human-readable short time value.
279
+ *
280
+ * @public
281
+ */
282
+ export const timeString = (value, decimalPlaces) => unitString(timeUnit, value, decimalPlaces);
283
+ /**
284
+ * Display a human-readable short time value.
285
+ *
286
+ * Bigint variant, only handle integer values.
287
+ *
288
+ * @public
289
+ */
290
+ export const timeStringBigint = (value) => unitStringBigint(timeUnit, value);
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ /**
17
+ * Check that Buffer can convert from/to Base64.
18
+ *
19
+ * @internal
20
+ */
21
+ export declare const haveBufferBase64: () => boolean;
22
+ /**
23
+ * Check that Buffer can convert from/to UTF8.
24
+ *
25
+ * @internal
26
+ */
27
+ export declare const haveBufferUTF8: () => boolean;
28
+ /**
29
+ * Check that Buffer can convert from/to hex.
30
+ *
31
+ * @internal
32
+ */
33
+ export declare const haveBufferHex: () => boolean;
34
+ /** @internal */
35
+ export declare const bufferAb2B64: (data: ArrayBuffer) => string;
36
+ /** @internal */
37
+ export declare const bufferB642Ab: (data: string, strict?: boolean) => ArrayBuffer;
38
+ /** @internal */
39
+ export declare const bufferBuf82Hex: (buf8: Uint8Array, addPrefix?: boolean) => string;
40
+ /** @internal */
41
+ export declare const bufferHex2Buf8: (hex: string) => Uint8Array;
42
+ /** @internal */
43
+ export declare const bufferBuf82B64: (buf8: Uint8Array) => string;
44
+ /** @internal */
45
+ export declare const bufferB642Buf8: (b64: string, strict?: boolean) => Uint8Array;
46
+ /** @internal */
47
+ export declare const bufferBuf82Utf8: (buf8: Uint8Array) => string;
48
+ /** @internal */
49
+ export declare const bufferUtf82Buf8: (utf8: string) => Uint8Array;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import { getArrayBuffer } from "../bits/arraybuffer.js";
17
+ import { b64Len, b64EffectiveData } from "../bits/base64.js";
18
+ import { clearHexInput } from "../bits/hex.js";
19
+ /** Check that Buffer is available somehow */
20
+ const haveBuffer = () => typeof Buffer !== "undefined";
21
+ /** Check that Buffer can convert from/to the given encoding */
22
+ const haveBufferEncoding = (encodingName, testValue) => {
23
+ if (!haveBuffer()) {
24
+ return false;
25
+ }
26
+ try {
27
+ return Buffer.from(testValue, encodingName).toString(encodingName) === testValue;
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ };
33
+ /**
34
+ * Check that Buffer can convert from/to Base64.
35
+ *
36
+ * @internal
37
+ */
38
+ export const haveBufferBase64 = () => haveBufferEncoding("base64", "abcd");
39
+ /**
40
+ * Check that Buffer can convert from/to UTF8.
41
+ *
42
+ * @internal
43
+ */
44
+ export const haveBufferUTF8 = () => haveBufferEncoding("utf8", "Spôŗjṫìck☺");
45
+ /**
46
+ * Check that Buffer can convert from/to hex.
47
+ *
48
+ * @internal
49
+ */
50
+ export const haveBufferHex = () => haveBufferEncoding("hex", "deadbeef");
51
+ /** @internal */
52
+ export const bufferAb2B64 = (data) => Buffer.from(data).toString("base64");
53
+ /** @internal */
54
+ export const bufferB642Ab = (data, strict) => {
55
+ const buffer = Buffer.from(strict === undefined ? data : b64EffectiveData(data, strict), "base64");
56
+ if (strict && buffer.byteLength !== b64Len(data, true))
57
+ throw new Error("Invalid base64 length");
58
+ return getArrayBuffer(buffer);
59
+ };
60
+ /** @internal */
61
+ export const bufferBuf82Hex = (buf8, addPrefix) => {
62
+ const hexResult = Buffer.from(buf8).toString("hex");
63
+ return addPrefix ? `0x${hexResult}` : hexResult;
64
+ };
65
+ /** @internal */
66
+ export const bufferHex2Buf8 = (hex) => new Uint8Array(Buffer.from(clearHexInput(hex), "hex"));
67
+ /** @internal */
68
+ export const bufferBuf82B64 = (buf8) => Buffer.from(buf8).toString("base64");
69
+ /** @internal */
70
+ export const bufferB642Buf8 = (b64, strict) => {
71
+ const result = new Uint8Array(Buffer.from(strict === undefined ? b64 : b64EffectiveData(b64, strict), "base64"));
72
+ if (strict && result.byteLength !== b64Len(b64, true))
73
+ throw new Error("Invalid base64 length");
74
+ return result;
75
+ };
76
+ /** @internal */
77
+ export const bufferBuf82Utf8 = (buf8) => Buffer.from(buf8).toString("utf8");
78
+ /** @internal */
79
+ export const bufferUtf82Buf8 = (utf8) => new Uint8Array(Buffer.from(utf8, "utf8"));
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ /**
17
+ * Crawl a byte buffer four bytes at a time.
18
+ *
19
+ * @internal
20
+ */
21
+ export default class FourBytes {
22
+ #private;
23
+ constructor(src: Uint8Array);
24
+ get byte1(): number | undefined;
25
+ get byte2(): number | undefined;
26
+ get byte3(): number | undefined;
27
+ get byte4(): number | undefined;
28
+ advance: (count: number) => void;
29
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ // The whole purpose of this class is to count to four.
17
+ /* eslint-disable @typescript-eslint/no-magic-numbers */
18
+ /**
19
+ * Crawl a byte buffer four bytes at a time.
20
+ *
21
+ * @internal
22
+ */
23
+ export default class FourBytes {
24
+ #src;
25
+ #cursor = 0;
26
+ constructor(src) {
27
+ this.#src = src;
28
+ }
29
+ get byte1() {
30
+ return this.#src[this.#cursor];
31
+ }
32
+ get byte2() {
33
+ return this.#src[this.#cursor + 1];
34
+ }
35
+ get byte3() {
36
+ return this.#src[this.#cursor + 2];
37
+ }
38
+ get byte4() {
39
+ return this.#src[this.#cursor + 3];
40
+ }
41
+ advance = (count) => {
42
+ this.#cursor += count;
43
+ };
44
+ }
45
+ /* eslint-enable @typescript-eslint/no-magic-numbers */
package/package.json ADDED
@@ -0,0 +1 @@
1
+ {"name":"@keeex/utils","version":"7.0.1","description":"Various utility functions for pure JavaScript","scripts":{},"author":"KeeeX SAS","contributors":[{"name":"Gabriel Paul \"Cley Faye\" Risterucci","email":"gabriel@keeex.net"}],"homepage":"https://keeex.me/oss","keywords":["utility"],"type":"module","license":"MIT","dependencies":{"@keeex/bubble_babble":"^3.0.1","@keeex/log":"^1.3.0","base64-arraybuffer":"^1.0.2","cron-parser":"^5.1.0","ms":"^2.1.3","text-encoding-shim":"^1.0.5"},"exports":{"./units.js":{"node":"./lib/units.js","browser":"./web/units.js","default":"./lib/units.js"},"./uint8array.js":{"node":"./lib/uint8array.js","browser":"./web/uint8array.js","default":"./lib/uint8array.js"},"./string.js":{"node":"./lib/string.js","browser":"./web/string.js","default":"./lib/string.js"},"./starttime.js":{"node":"./lib/starttime.js","browser":"./web/starttime.js","default":"./lib/starttime.js"},"./promise.js":{"node":"./lib/promise.js","browser":"./web/promise.js","default":"./lib/promise.js"},"./path.js":{"node":"./lib/path.js","browser":"./web/path.js","default":"./lib/path.js"},"./number.js":{"node":"./lib/number.js","browser":"./web/number.js","default":"./lib/number.js"},"./json.js":{"node":"./lib/json.js","browser":"./web/json.js","default":"./lib/json.js"},"./idx.js":{"node":"./lib/idx.js","browser":"./web/idx.js","default":"./lib/idx.js"},"./hex.js":{"node":"./lib/hex.js","browser":"./web/hex.js","default":"./lib/hex.js"},"./global.js":{"node":"./lib/global.js","browser":"./web/global.js","default":"./lib/global.js"},"./error.js":{"node":"./lib/error.js","browser":"./web/error.js","default":"./lib/error.js"},"./dict.js":{"node":"./lib/dict.js","browser":"./web/dict.js","default":"./lib/dict.js"},"./cron.js":{"node":"./lib/cron.js","browser":"./web/cron.js","default":"./lib/cron.js"},"./consts.js":{"node":"./lib/consts.js","browser":"./web/consts.js","default":"./lib/consts.js"},"./bytebuffer.js":{"node":"./lib/bytebuffer.js","browser":"./web/bytebuffer.js","default":"./lib/bytebuffer.js"},"./benchmark.js":{"node":"./lib/benchmark.js","browser":"./web/benchmark.js","default":"./lib/benchmark.js"},"./base64.js":{"node":"./lib/base64.js","browser":"./web/base64.js","default":"./lib/base64.js"},"./base58.js":{"node":"./lib/base58.js","browser":"./web/base58.js","default":"./lib/base58.js"},"./arraybuffer.js":{"node":"./lib/arraybuffer.js","browser":"./web/arraybuffer.js","default":"./lib/arraybuffer.js"},"./array.js":{"node":"./lib/array.js","browser":"./web/array.js","default":"./lib/array.js"},"./marshalling/unmarshaller.js":{"node":"./lib/marshalling/unmarshaller.js","browser":"./web/marshalling/unmarshaller.js","default":"./lib/marshalling/unmarshaller.js"},"./marshalling/marshaller.js":{"node":"./lib/marshalling/marshaller.js","browser":"./web/marshalling/marshaller.js","default":"./lib/marshalling/marshaller.js"},"./types/utils.js":{"node":"./lib/types/utils.js","browser":"./web/types/utils.js","default":"./lib/types/utils.js"},"./types/types.js":{"node":"./lib/types/types.js","browser":"./web/types/types.js","default":"./lib/types/types.js"},"./types/record.js":{"node":"./lib/types/record.js","browser":"./web/types/record.js","default":"./lib/types/record.js"},"./types/primitive.js":{"node":"./lib/types/primitive.js","browser":"./web/types/primitive.js","default":"./lib/types/primitive.js"},"./types/predicateerror.js":{"node":"./lib/types/predicateerror.js","browser":"./web/types/predicateerror.js","default":"./lib/types/predicateerror.js"},"./types/enum.js":{"node":"./lib/types/enum.js","browser":"./web/types/enum.js","default":"./lib/types/enum.js"},"./types/array.js":{"node":"./lib/types/array.js","browser":"./web/types/array.js","default":"./lib/types/array.js"},"./async/timecache.js":{"node":"./lib/async/timecache.js","browser":"./web/async/timecache.js","default":"./lib/async/timecache.js"},"./async/queues.js":{"node":"./lib/async/queues.js","browser":"./web/async/queues.js","default":"./lib/async/queues.js"},"./async/keycache.js":{"node":"./lib/async/keycache.js","browser":"./web/async/keycache.js","default":"./lib/async/keycache.js"},"./async/deferredpromise.js":{"node":"./lib/async/deferredpromise.js","browser":"./web/async/deferredpromise.js","default":"./lib/async/deferredpromise.js"},"./async/asynctrigger.js":{"node":"./lib/async/asynctrigger.js","browser":"./web/async/asynctrigger.js","default":"./lib/async/asynctrigger.js"}},"files":["/lib","/web"]}