@stellar-expert/formatter 2.3.0 → 2.5.0

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.
package/README.md CHANGED
@@ -3,11 +3,7 @@
3
3
  ## Installation
4
4
 
5
5
  ```
6
- "dependencies": {
7
- "@stellar-expert/formatter": "github:stellar-expert/formatter#v2.0.0",
8
- ...
9
- }
10
- }
6
+ npm i @stellar-expert/formatter
11
7
  ```
12
8
 
13
9
  ## Usage
@@ -0,0 +1,368 @@
1
+ (function webpackUniversalModuleDefinition(root, factory) {
2
+ if(typeof exports === 'object' && typeof module === 'object')
3
+ module.exports = factory();
4
+ else if(typeof define === 'function' && define.amd)
5
+ define([], factory);
6
+ else if(typeof exports === 'object')
7
+ exports["formatter"] = factory();
8
+ else
9
+ root["formatter"] = factory();
10
+ })(this, () => {
11
+ return /******/ (() => { // webpackBootstrap
12
+ /******/ "use strict";
13
+ /******/ // The require scope
14
+ /******/ var __webpack_require__ = {};
15
+ /******/
16
+ /************************************************************************/
17
+ /******/ /* webpack/runtime/define property getters */
18
+ /******/ (() => {
19
+ /******/ // define getter functions for harmony exports
20
+ /******/ __webpack_require__.d = (exports, definition) => {
21
+ /******/ for(var key in definition) {
22
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
23
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
24
+ /******/ }
25
+ /******/ }
26
+ /******/ };
27
+ /******/ })();
28
+ /******/
29
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
30
+ /******/ (() => {
31
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
32
+ /******/ })();
33
+ /******/
34
+ /************************************************************************/
35
+ var __webpack_exports__ = {};
36
+
37
+ // EXPORTS
38
+ __webpack_require__.d(__webpack_exports__, {
39
+ "default": () => (/* binding */ commonjs)
40
+ });
41
+
42
+ ;// CONCATENATED MODULE: ./src/truncation.js
43
+ /**
44
+ * Remove trailing zero symbols from a formatted numeric string
45
+ * @param {String} value
46
+ * @return {String}
47
+ */
48
+ function stripTrailingZeros(value) {
49
+ if (typeof value !== 'string') return value;
50
+ let [int, reminder] = value.split('.');
51
+ if (!reminder) return int;
52
+ reminder = reminder.replace(/0+$/, '');
53
+ if (!reminder.length) return int;
54
+ return int + '.' + reminder;
55
+ }
56
+
57
+ /**
58
+ * Truncate strings longer than N symbols replacing characters in the middle with ellipsis
59
+ * @param {String} value - Original string
60
+ * @param {Number} [symbols] - Maximum string length
61
+ * @return {String}
62
+ */
63
+ function shortenString(value, symbols = 8) {
64
+ if (!value || value.length <= symbols) return value;
65
+ const affixLength = Math.max(2, Math.floor(symbols / 2));
66
+ return value.substring(0, affixLength) + '…' + value.substring(value.length - affixLength);
67
+ }
68
+ ;// CONCATENATED MODULE: ./src/stroops.js
69
+
70
+
71
+ /**
72
+ * Convert value in stroops (Int64 amount) to the normal string representation
73
+ * @param {String|Number|BigInt} valueInStroops
74
+ * @return {String}
75
+ */
76
+ function fromStroops(valueInStroops) {
77
+ try {
78
+ let parsed = typeof valueInStroops === 'bigint' ? valueInStroops : BigInt(valueInStroops.toString().replace(/\.\d*/, ''));
79
+ let negative = false;
80
+ if (parsed < 0n) {
81
+ negative = true;
82
+ parsed *= -1n;
83
+ }
84
+ const int = parsed / 10000000n;
85
+ const fract = parsed % 10000000n;
86
+ let res = int.toString();
87
+ if (fract) {
88
+ res += '.' + fract.toString().padStart(7, '0');
89
+ }
90
+ if (negative) {
91
+ res = '-' + res;
92
+ }
93
+ return stripTrailingZeros(res);
94
+ } catch (e) {
95
+ return '0';
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Convert arbitrary stringified amount to int64 representation
101
+ * @param {String|Number} value
102
+ * @return {BigInt}
103
+ */
104
+ function toStroops(value) {
105
+ if (!value) return 0n;
106
+ if (typeof value === 'number') {
107
+ value = value.toFixed(7);
108
+ }
109
+ if (typeof value !== 'string' || !/^-?[\d.,]+$/.test(value)) return 0n; //invalid format
110
+ try {
111
+ let [int, decimal = '0'] = value.split('.', 2);
112
+ let negative = false;
113
+ if (int.startsWith('-')) {
114
+ negative = true;
115
+ int = int.slice(1);
116
+ }
117
+ let res = BigInt(int) * 10000000n + BigInt(decimal.slice(0, 7).padEnd(7, '0'));
118
+ if (negative) {
119
+ res *= -1n;
120
+ if (res < -0x8000000000000000n)
121
+ //overflow
122
+ return 0n;
123
+ } else if (res > 0xFFFFFFFFFFFFFFFFn)
124
+ //overflow
125
+ return 0n;
126
+ return res;
127
+ } catch (e) {
128
+ return 0n;
129
+ }
130
+ }
131
+ ;// CONCATENATED MODULE: ./src/numeric-format.js
132
+
133
+
134
+ function addDecimalsSeparators(value, separator = ',', trimTrailingZeros = true) {
135
+ //TODO: use Bignumber.toFormat() method instead
136
+ //split numeric to parts
137
+ let [int, reminder] = value.split('.');
138
+ let res = '';
139
+ //split digit groups
140
+ while (int.length > 3) {
141
+ res = separator + int.substring(int.length - 3) + res;
142
+ int = int.substring(0, int.length - 3);
143
+ }
144
+ //strip negative sign
145
+ if (int === '-') {
146
+ res = res.substring(1);
147
+ }
148
+ res = int + res;
149
+ if (reminder) {
150
+ res += '.' + reminder;
151
+ }
152
+ if (trimTrailingZeros) {
153
+ res = stripTrailingZeros(res);
154
+ }
155
+ return res;
156
+ }
157
+
158
+ /**
159
+ * Check if a provided value can be safely used as token amount in Stellar operations
160
+ * @param {String} value
161
+ * @param {Boolean} denominate
162
+ * @param {Boolean} nonZero
163
+ * @return {Boolean}
164
+ */
165
+ function isValidInt64Amount(value, denominate = true, nonZero = false) {
166
+ try {
167
+ const parsed = denominate ? toStroops(value) : BigInt(value);
168
+ if (nonZero) {
169
+ if (parsed <= 0n) return false;
170
+ } else {
171
+ if (parsed < 0n) return false;
172
+ }
173
+ return parsed <= 9223372036854775807n;
174
+ } catch (e) {
175
+ return false;
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Format a number with specified precision and decimals separator
181
+ * @param {String|Number|BigInt} value - Numeric value to format
182
+ * @param {Number} [precision] - Desired precision (7 digits by default)
183
+ * @param {String} [separator] - Decimals separator
184
+ * @return {String}
185
+ */
186
+ function formatWithPrecision(value, precision = 7, separator = ',') {
187
+ return addDecimalsSeparators(setPrecision(value, precision), separator, true);
188
+ }
189
+
190
+ /**
191
+ * Format a number using automatically determined precision
192
+ * @param {String|Number} value - Numeric value to format
193
+ * @param {String} [separator] - Decimals separator
194
+ * @return {String}
195
+ */
196
+ function formatWithAutoPrecision(value, separator = ',') {
197
+ if (!value) return '0';
198
+ const p = Math.ceil(Math.log10(parseFloat(value)));
199
+ let reminderPrecision = p > 1 ? 3 - p : Math.abs(p) + 2;
200
+ if (reminderPrecision < 0) {
201
+ reminderPrecision = 0;
202
+ }
203
+ return formatWithPrecision(value, reminderPrecision, separator);
204
+ }
205
+
206
+ /**
207
+ * Convert a number to a human-readable format using abbreviation
208
+ * @param {Number} value - Value to format
209
+ * @param {Number} [decimals] - Precision of the abbreviated string to retain
210
+ * @return {String}
211
+ */
212
+ function formatWithAbbreviation(value, decimals = 2) {
213
+ let abs = Math.abs(value);
214
+ const tier = Math.log10(abs) / 3 | 0;
215
+ if (tier <= 0) return formatWithAutoPrecision(value);
216
+ const suffix = ['', 'K', 'M', 'G', 'T', 'P'][tier];
217
+ abs = stripTrailingZeros((abs / Math.pow(10, tier * 3)).toFixed(decimals));
218
+ return `${value < 0 ? '-' : ''}${abs || '0'}${suffix}`;
219
+ }
220
+
221
+ /**
222
+ * Format a number with rounding to specific precision group
223
+ * @param {String|Number|BigInt} value - Value to format
224
+ * @param {Number} group - Logarithmic group rate for rounding
225
+ * @return {String}
226
+ */
227
+ function formatWithGrouping(value, group) {
228
+ if (!value) return '0';
229
+ const precision = group >= 1 || group === 0 ? 0 : Math.abs(Math.log10(group));
230
+ if (group >= 1) {
231
+ value = Math.ceil(value / group) * group;
232
+ }
233
+ return formatWithPrecision(value, precision);
234
+ }
235
+
236
+ /**
237
+ * Format a number as price with specified significant digits precision
238
+ * @param {String|Number|Bignumber} value - Value to format
239
+ * @param {Number} significantDigits - Significant digits for automatic formatting
240
+ * @return {String}
241
+ */
242
+ function formatPrice(value, significantDigits = 4) {
243
+ const primitive = typeof value === 'number' ? value.toFixed(7) : value.toString();
244
+ const [int, fract] = primitive.split('.');
245
+ if (int.replace('-', '') !== '0') {
246
+ significantDigits -= int.length;
247
+ if (significantDigits < 0) {
248
+ significantDigits = 0;
249
+ }
250
+ } else {
251
+ if (!(fract > 0)) return '0';
252
+ significantDigits = Math.max(Math.ceil(Math.abs(Math.log10(parseFloat('.' + fract)))), significantDigits);
253
+ }
254
+ return formatWithPrecision(value, significantDigits, '');
255
+ }
256
+
257
+ /**
258
+ * Format amount according to default Stellar precision
259
+ * @param {Number|String} amount - Value to format
260
+ * @return {String}
261
+ */
262
+ function adjustPrecision(amount = '0') {
263
+ return stripTrailingZeros(setPrecision(amount, 7));
264
+ }
265
+ function setPrecision(amount, precision) {
266
+ if (typeof amount === 'number') {
267
+ amount = amount.toFixed(precision);
268
+ } else {
269
+ amount = amount.toString();
270
+ const sidx = amount.indexOf('.');
271
+ if (sidx >= 0) {
272
+ amount = amount.slice(0, sidx + precision + 1);
273
+ }
274
+ }
275
+ return amount;
276
+ }
277
+ ;// CONCATENATED MODULE: ./src/timestamp-format.js
278
+ /**
279
+ * Convert any timestamp representation to a valid date format
280
+ * @param {Date|String|Number} date - Date to parse
281
+ * @param {Boolean} [autoUnixFormatDetection] - Intelligent guess for dates already represented as UNIX timestamp (true by default)
282
+ * @return {Date} Parsed date
283
+ */
284
+ function normalizeDate(date, autoUnixFormatDetection = true) {
285
+ //try parse string representation
286
+ if (typeof date === 'string') {
287
+ if (!/^\d+$/.test(date)) {
288
+ if (!date.endsWith('Z')) {
289
+ date += 'Z';
290
+ }
291
+ date = new Date(date);
292
+ } else {
293
+ date = parseInt(date);
294
+ }
295
+ }
296
+ //parse numeric representation
297
+ if (typeof date === 'number') {
298
+ //input resembles a UNIX timestamp
299
+ if (date < 2147483648 && autoUnixFormatDetection) {
300
+ date *= 1000;
301
+ }
302
+ date = new Date(date);
303
+ }
304
+ //check validity
305
+ if (!(date instanceof Date) || isNaN(date.valueOf())) throw new Error('Invalid timestamp ' + date);
306
+ return date;
307
+ }
308
+
309
+ /**
310
+ * Convert date to a numeric UNIX timestamp representation
311
+ * @param {Date|String|Number} date - Date to convert
312
+ * @return {Number} UNIX timestamp
313
+ */
314
+ function toUnixTimestamp(date) {
315
+ return Math.floor(normalizeDate(date).getTime() / 1000);
316
+ }
317
+
318
+ /**
319
+ * Convert date to ISO-like human-readable format
320
+ * @param {Date|String|Number} date - Date to convert
321
+ * @return {String}
322
+ */
323
+ function formatDateUTC(date) {
324
+ return normalizeDate(date).toISOString().replace(/(T|\.\d+Z)/g, ' ') // make it more human friendly
325
+ .trim();
326
+ }
327
+ ;// CONCATENATED MODULE: ./src/approximation.js
328
+ /**
329
+ * Convert rational price representation to Number
330
+ * @param {{n: Number, d: Number}|Number|String} price
331
+ * @return {Number}
332
+ */
333
+ function approximatePrice(price) {
334
+ if (!price) return 0;
335
+ if (price.n) return price.n / price.d;
336
+ if (typeof price === 'string') return parseFloat(price);
337
+ return price;
338
+ }
339
+ ;// CONCATENATED MODULE: ./src/commonjs.js
340
+
341
+
342
+
343
+
344
+
345
+ const formatter = {
346
+ adjustPrecision: adjustPrecision,
347
+ formatWithAutoPrecision: formatWithAutoPrecision,
348
+ formatWithAbbreviation: formatWithAbbreviation,
349
+ formatWithGrouping: formatWithGrouping,
350
+ formatWithPrecision: formatWithPrecision,
351
+ formatPrice: formatPrice,
352
+ isValidInt64Amount: isValidInt64Amount,
353
+ formatDateUTC: formatDateUTC,
354
+ normalizeDate: normalizeDate,
355
+ toUnixTimestamp: toUnixTimestamp,
356
+ approximatePrice: approximatePrice,
357
+ shortenString: shortenString,
358
+ stripTrailingZeros: stripTrailingZeros,
359
+ toStroops: toStroops,
360
+ fromStroops: fromStroops
361
+ };
362
+ /* harmony default export */ const commonjs = (formatter);
363
+ __webpack_exports__ = __webpack_exports__["default"];
364
+ /******/ return __webpack_exports__;
365
+ /******/ })()
366
+ ;
367
+ });
368
+ //# sourceMappingURL=formatter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatter.js","mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;;UCVA;UACA;;;;;WCDA;WACA;WACA;WACA;WACA,yCAAyC,wCAAwC;WACjF;WACA;WACA;;;;;WCPA;;;;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACO,SAASA,kBAAkBA,CAACC,KAAK,EAAE;EACtC,IAAI,OAAOA,KAAK,KAAK,QAAQ,EACzB,OAAOA,KAAK;EAChB,IAAI,CAACC,GAAG,EAAEC,QAAQ,CAAC,GAAGF,KAAK,CAACG,KAAK,CAAC,GAAG,CAAC;EACtC,IAAI,CAACD,QAAQ,EACT,OAAOD,GAAG;EACdC,QAAQ,GAAGA,QAAQ,CAACE,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;EACtC,IAAI,CAACF,QAAQ,CAACG,MAAM,EAChB,OAAOJ,GAAG;EACd,OAAOA,GAAG,GAAG,GAAG,GAAGC,QAAQ;AAC/B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,SAASI,aAAaA,CAACN,KAAK,EAAEO,OAAO,GAAG,CAAC,EAAE;EAC9C,IAAI,CAACP,KAAK,IAAIA,KAAK,CAACK,MAAM,IAAIE,OAAO,EACjC,OAAOP,KAAK;EAChB,MAAMQ,WAAW,GAAGC,IAAI,CAACC,GAAG,CAAC,CAAC,EAAED,IAAI,CAACE,KAAK,CAACJ,OAAO,GAAG,CAAC,CAAC,CAAC;EACxD,OAAOP,KAAK,CAACY,SAAS,CAAC,CAAC,EAAEJ,WAAW,CAAC,GAAG,GAAG,GAAGR,KAAK,CAACY,SAAS,CAACZ,KAAK,CAACK,MAAM,GAAGG,WAAW,CAAC;AAC9F;;AC5BkD;;AAElD;AACA;AACA;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CAAC,IAAIE,KAAK,CAACL,IAAI,CAACM,OAAO,CAAC,CAAC,CAAC,EAChD,MAAM,IAAIC,KAAK,CAAC,oBAAoB,GAAGP,IAAI,CAAC;EAChD,OAAOA,IAAI;AACf;;AAEA;AACA;AACA;AACA;AACA;AACO,SAASQ,eAAeA,CAACR,IAAI,EAAE;EAClC,OAAOpD,IAAI,CAACE,KAAK,CAACiD,aAAa,CAACC,IAAI,CAAC,CAACS,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;AAC3D;;AAEA;AACA;AACA;AACA;AACA;AACO,SAASC,aAAaA,CAACV,IAAI,EAAE;EAChC,OAAOD,aAAa,CAACC,IAAI,CAAC,CACrBW,WAAW,CAAC,CAAC,CACbpE,OAAO,CAAC,aAAa,EAAE,GAAG,CAAC,CAAC;EAAA,CAC5BqE,IAAI,CAAC,CAAC;AACf;;ACnDA;AACA;AACA;AACA;AACA;AACO,SAASC,gBAAgBA,CAACC,KAAK,EAAE;EACpC,IAAI,CAACA,KAAK,EACN,OAAO,CAAC;EACZ,IAAIA,KAAK,CAACC,CAAC,EACP,OAAOD,KAAK,CAACC,CAAC,GAAGD,KAAK,CAACE,CAAC;EAC5B,IAAI,OAAOF,KAAK,KAAK,QAAQ,EACzB,OAAOhC,UAAU,CAACgC,KAAK,CAAC;EAC5B,OAAOA,KAAK;AAChB;;ACL4B;AACuD;AAChC;AACc;AACd;AAEnD,MAAMG,SAAS,GAAG;EACdtB,eAAe;EACfjB,uBAAuB;EACvBO,sBAAsB;EACtBK,kBAAkB;EAClBf,mBAAmB;EACnBiB,WAAW;EACXpB,kBAAkB;EAClBsC,aAAa;EACbX,aAAa;EACbS,eAAe;EACfK,gBAAgB;EAChBpE,aAAa;EACbP,kBAAkB;EAClBwB,SAAS;EACTV,WAAWA,EAAAA,WAAAA;AACf,CAAC;AAED,+CAAeiE,SAAS,E","sources":["webpack://formatter/webpack/universalModuleDefinition","webpack://formatter/webpack/bootstrap","webpack://formatter/webpack/runtime/define property getters","webpack://formatter/webpack/runtime/hasOwnProperty shorthand","webpack://formatter/./src/truncation.js","webpack://formatter/./src/stroops.js","webpack://formatter/./src/numeric-format.js","webpack://formatter/./src/timestamp-format.js","webpack://formatter/./src/approximation.js","webpack://formatter/./src/commonjs.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"formatter\"] = factory();\n\telse\n\t\troot[\"formatter\"] = factory();\n})(this, () => {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","/**\n * Remove trailing zero symbols from a formatted numeric string\n * @param {String} value\n * @return {String}\n */\nexport function stripTrailingZeros(value) {\n if (typeof value !== 'string')\n return value\n let [int, reminder] = value.split('.')\n if (!reminder)\n return int\n reminder = reminder.replace(/0+$/, '')\n if (!reminder.length)\n return int\n return int + '.' + reminder\n}\n\n/**\n * Truncate strings longer than N symbols replacing characters in the middle with ellipsis\n * @param {String} value - Original string\n * @param {Number} [symbols] - Maximum string length\n * @return {String}\n */\nexport function shortenString(value, symbols = 8) {\n if (!value || value.length <= symbols)\n return value\n const affixLength = Math.max(2, Math.floor(symbols / 2))\n return value.substring(0, affixLength) + '…' + value.substring(value.length - affixLength)\n}","import {stripTrailingZeros} from './truncation.js'\n\n/**\n * Convert value in stroops (Int64 amount) to the normal string representation\n * @param {String|Number|BigInt} valueInStroops\n * @return {String}\n */\nexport function fromStroops(valueInStroops) {\n try {\n let parsed = typeof valueInStroops === 'bigint' ?\n valueInStroops :\n BigInt(valueInStroops.toString().replace(/\\.\\d*/,''))\n let negative = false\n if (parsed < 0n) {\n negative = true\n parsed *= -1n\n }\n const int = parsed / 10000000n\n const fract = parsed % 10000000n\n let res = int.toString()\n if (fract) {\n res += '.' + fract.toString().padStart(7, '0')\n }\n if (negative) {\n res = '-' + res\n }\n return stripTrailingZeros(res)\n } catch (e) {\n return '0'\n }\n}\n\n\n/**\n * Convert arbitrary stringified amount to int64 representation\n * @param {String|Number} value\n * @return {BigInt}\n */\nexport function toStroops(value) {\n if (!value)\n return 0n\n if (typeof value === 'number') {\n value = value.toFixed(7)\n }\n if (typeof value !== 'string' || !/^-?[\\d.,]+$/.test(value))\n return 0n //invalid format\n try {\n let [int, decimal = '0'] = value.split('.', 2)\n let negative = false\n if (int.startsWith('-')) {\n negative = true\n int = int.slice(1)\n }\n let res = BigInt(int) * 10000000n + BigInt(decimal.slice(0, 7).padEnd(7, '0'))\n if (negative) {\n res *= -1n\n if (res < -0x8000000000000000n) //overflow\n return 0n\n } else if (res > 0xFFFFFFFFFFFFFFFFn) //overflow\n return 0n\n return res\n } catch (e) {\n return 0n\n }\n}","import {stripTrailingZeros} from './truncation.js'\nimport {toStroops} from './stroops.js'\n\nfunction addDecimalsSeparators(value, separator = ',', trimTrailingZeros = true) {\n //TODO: use Bignumber.toFormat() method instead\n //split numeric to parts\n let [int, reminder] = value.split('.')\n let res = ''\n //split digit groups\n while (int.length > 3) {\n res = separator + int.substring(int.length - 3) + res\n int = int.substring(0, int.length - 3)\n }\n //strip negative sign\n if (int === '-') {\n res = res.substring(1)\n }\n res = int + res\n if (reminder) {\n res += '.' + reminder\n }\n if (trimTrailingZeros) {\n res = stripTrailingZeros(res)\n }\n return res\n}\n\n/**\n * Check if a provided value can be safely used as token amount in Stellar operations\n * @param {String} value\n * @param {Boolean} denominate\n * @param {Boolean} nonZero\n * @return {Boolean}\n */\nexport function isValidInt64Amount(value, denominate = true, nonZero = false) {\n try {\n const parsed = denominate ?\n toStroops(value) :\n BigInt(value)\n if (nonZero) {\n if (parsed <= 0n)\n return false\n } else {\n if (parsed < 0n)\n return false\n }\n return parsed <= 9223372036854775807n\n } catch (e) {\n return false\n }\n}\n\n/**\n * Format a number with specified precision and decimals separator\n * @param {String|Number|BigInt} value - Numeric value to format\n * @param {Number} [precision] - Desired precision (7 digits by default)\n * @param {String} [separator] - Decimals separator\n * @return {String}\n */\nexport function formatWithPrecision(value, precision = 7, separator = ',') {\n return addDecimalsSeparators(setPrecision(value, precision), separator, true)\n}\n\n/**\n * Format a number using automatically determined precision\n * @param {String|Number} value - Numeric value to format\n * @param {String} [separator] - Decimals separator\n * @return {String}\n */\nexport function formatWithAutoPrecision(value, separator = ',') {\n if (!value)\n return '0'\n const p = Math.ceil(Math.log10(parseFloat(value)))\n let reminderPrecision = p > 1 ?\n (3 - p) :\n (Math.abs(p) + 2)\n if (reminderPrecision < 0) {\n reminderPrecision = 0\n }\n return formatWithPrecision(value, reminderPrecision, separator)\n}\n\n/**\n * Convert a number to a human-readable format using abbreviation\n * @param {Number} value - Value to format\n * @param {Number} [decimals] - Precision of the abbreviated string to retain\n * @return {String}\n */\nexport function formatWithAbbreviation(value, decimals = 2) {\n let abs = Math.abs(value)\n const tier = Math.log10(abs) / 3 | 0\n\n if (tier <= 0)\n return formatWithAutoPrecision(value)\n\n const suffix = ['', 'K', 'M', 'G', 'T', 'P'][tier]\n abs = stripTrailingZeros((abs / Math.pow(10, tier * 3)).toFixed(decimals))\n return `${value < 0 ? '-' : ''}${abs || '0'}${suffix}`\n}\n\n/**\n * Format a number with rounding to specific precision group\n * @param {String|Number|BigInt} value - Value to format\n * @param {Number} group - Logarithmic group rate for rounding\n * @return {String}\n */\nexport function formatWithGrouping(value, group) {\n if (!value)\n return '0'\n const precision = (group >= 1 || group === 0) ?\n 0 :\n Math.abs(Math.log10(group))\n if (group >= 1) {\n value = Math.ceil(value / group) * group\n }\n return formatWithPrecision(value, precision)\n}\n\n/**\n * Format a number as price with specified significant digits precision\n * @param {String|Number|Bignumber} value - Value to format\n * @param {Number} significantDigits - Significant digits for automatic formatting\n * @return {String}\n */\nexport function formatPrice(value, significantDigits = 4) {\n const primitive = (typeof value === 'number') ?\n value.toFixed(7) :\n value.toString()\n const [int, fract] = primitive.split('.')\n if (int.replace('-', '') !== '0') {\n significantDigits -= int.length\n if (significantDigits < 0) {\n significantDigits = 0\n }\n } else {\n if (!(fract > 0))\n return '0'\n significantDigits = Math.max(Math.ceil(Math.abs(Math.log10(parseFloat('.' + fract)))), significantDigits)\n }\n return formatWithPrecision(value, significantDigits, '')\n}\n\n/**\n * Format amount according to default Stellar precision\n * @param {Number|String} amount - Value to format\n * @return {String}\n */\nexport function adjustPrecision(amount = '0') {\n return stripTrailingZeros(setPrecision(amount, 7))\n}\n\nfunction setPrecision(amount, precision) {\n if (typeof amount === 'number') {\n amount = amount.toFixed(precision)\n } else {\n amount = amount.toString()\n const sidx = amount.indexOf('.')\n if (sidx >= 0) {\n amount = amount.slice(0, sidx + precision + 1)\n }\n }\n return amount\n}","/**\n * Convert any timestamp representation to a valid date format\n * @param {Date|String|Number} date - Date to parse\n * @param {Boolean} [autoUnixFormatDetection] - Intelligent guess for dates already represented as UNIX timestamp (true by default)\n * @return {Date} Parsed date\n */\nexport function normalizeDate(date, autoUnixFormatDetection = true) {\n //try parse string representation\n if (typeof date === 'string') {\n if (!/^\\d+$/.test(date)) {\n if (!date.endsWith('Z')) {\n date += 'Z'\n }\n date = new Date(date)\n } else {\n date = parseInt(date)\n }\n }\n //parse numeric representation\n if (typeof date === 'number') {\n //input resembles a UNIX timestamp\n if (date < 2147483648 && autoUnixFormatDetection) {\n date *= 1000\n }\n date = new Date(date)\n }\n //check validity\n if (!(date instanceof Date) || isNaN(date.valueOf()))\n throw new Error('Invalid timestamp ' + date)\n return date\n}\n\n/**\n * Convert date to a numeric UNIX timestamp representation\n * @param {Date|String|Number} date - Date to convert\n * @return {Number} UNIX timestamp\n */\nexport function toUnixTimestamp(date) {\n return Math.floor(normalizeDate(date).getTime() / 1000)\n}\n\n/**\n * Convert date to ISO-like human-readable format\n * @param {Date|String|Number} date - Date to convert\n * @return {String}\n */\nexport function formatDateUTC(date) {\n return normalizeDate(date)\n .toISOString()\n .replace(/(T|\\.\\d+Z)/g, ' ') // make it more human friendly\n .trim()\n}","/**\n * Convert rational price representation to Number\n * @param {{n: Number, d: Number}|Number|String} price\n * @return {Number}\n */\nexport function approximatePrice(price) {\n if (!price)\n return 0\n if (price.n)\n return price.n / price.d\n if (typeof price === 'string')\n return parseFloat(price)\n return price\n}","import {\r\n adjustPrecision,\r\n formatWithAutoPrecision,\r\n formatWithAbbreviation,\r\n formatWithGrouping,\r\n formatWithPrecision,\r\n formatPrice,\r\n isValidInt64Amount\r\n} from './numeric-format.js'\r\nimport {formatDateUTC, normalizeDate, toUnixTimestamp} from './timestamp-format.js'\r\nimport {approximatePrice} from './approximation.js'\r\nimport {shortenString, stripTrailingZeros} from './truncation.js'\r\nimport {toStroops, fromStroops} from './stroops.js'\r\n\r\nconst formatter = {\r\n adjustPrecision,\r\n formatWithAutoPrecision,\r\n formatWithAbbreviation,\r\n formatWithGrouping,\r\n formatWithPrecision,\r\n formatPrice,\r\n isValidInt64Amount,\r\n formatDateUTC,\r\n normalizeDate,\r\n toUnixTimestamp,\r\n approximatePrice,\r\n shortenString,\r\n stripTrailingZeros,\r\n toStroops,\r\n fromStroops\r\n}\r\n\r\nexport default formatter"],"names":["stripTrailingZeros","value","int","reminder","split","replace","length","shortenString","symbols","affixLength","Math","max","floor","substring","fromStroops","valueInStroops","parsed","BigInt","toString","negative","fract","res","padStart","e","toStroops","toFixed","test","decimal","startsWith","slice","padEnd","addDecimalsSeparators","separator","trimTrailingZeros","isValidInt64Amount","denominate","nonZero","formatWithPrecision","precision","setPrecision","formatWithAutoPrecision","p","ceil","log10","parseFloat","reminderPrecision","abs","formatWithAbbreviation","decimals","tier","suffix","pow","formatWithGrouping","group","formatPrice","significantDigits","primitive","adjustPrecision","amount","sidx","indexOf","normalizeDate","date","autoUnixFormatDetection","endsWith","Date","parseInt","isNaN","valueOf","Error","toUnixTimestamp","getTime","formatDateUTC","toISOString","trim","approximatePrice","price","n","d","formatter"],"sourceRoot":""}
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "@stellar-expert/formatter",
3
- "version": "2.3.0",
3
+ "version": "2.5.0",
4
4
  "description": "Formatting utils and common formats for numeric, string, timestamp and binary data",
5
- "type": "module",
6
- "main": "index.js",
7
- "module": "index.js",
5
+ "main": "./lib/formatter.js",
6
+ "module": "./src/index.js",
8
7
  "sideEffects": false,
8
+ "exports": {
9
+ "import": "./src/index.js",
10
+ "require": "./lib/formatter.js"
11
+ },
9
12
  "scripts": {
13
+ "build": "webpack --mode=production --config webpack.config.cjs",
10
14
  "test": "jest"
11
15
  },
12
16
  "repository": {
@@ -19,6 +23,11 @@
19
23
  "url": "https://github.com/stellar-expert/formatter/issues"
20
24
  },
21
25
  "devDependencies": {
22
- "jest": "^29.7.0"
26
+ "@babel/core": "^7.24.8",
27
+ "@babel/preset-env": "^7.24.8",
28
+ "babel-loader": "^9.1.3",
29
+ "jest": "^29.7.0",
30
+ "webpack": "^5.93.0",
31
+ "webpack-cli": "^5.1.4"
23
32
  }
24
33
  }
package/src/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export * from './numeric-format.js'
2
+ export * from './timestamp-format.js'
3
+ export * from './approximation.js'
4
+ export * from './truncation.js'
5
+ export * from './stroops.js'
6
+
7
+ //changes
8
+ //formatLongHex -> shortenString
9
+ //adjustAmount -> adjustPrecision
10
+ //formatCurrency deprecated
package/index.js DELETED
@@ -1,10 +0,0 @@
1
- export * from './src/numeric-format.js'
2
- export * from './src/timestamp-format.js'
3
- export * from './src/approximation.js'
4
- export * from './src/truncation.js'
5
- export * from './src/stroops.js'
6
-
7
- //changes
8
- //formatLongHex -> shortenString
9
- //adjustAmount -> adjustPrecision
10
- //formatCurrency deprecated