@valkyriestudios/utils 11.7.0 → 12.1.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/date/format.js ADDED
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const is_1 = require("./is");
4
+ const DEFAULT_LOCALE = 'en-US';
5
+ let DEFAULT_TZ = 'UTC';
6
+ try {
7
+ DEFAULT_TZ = Intl.DateTimeFormat().resolvedOptions().timeZone;
8
+ }
9
+ catch (err) {
10
+ }
11
+ finally {
12
+ if (typeof DEFAULT_TZ !== 'string')
13
+ DEFAULT_TZ = 'UTC';
14
+ }
15
+ const escape_rgx = /\[[\s\S]+?]/g;
16
+ const intl_formatters = new Map();
17
+ const spec_cache = new Map();
18
+ const zone_offset_cache = new Map();
19
+ function DOY(d) {
20
+ return Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 86400000);
21
+ }
22
+ function toZone(date, zone) {
23
+ const ckey = `${zone}:${date.getUTCFullYear()}${DOY(date)}`;
24
+ if (zone_offset_cache.has(ckey))
25
+ return new Date(date.getTime() + zone_offset_cache.get(ckey));
26
+ const client_time = date.getTime();
27
+ let zone_time = false;
28
+ try {
29
+ zone_time = new Date(date.toLocaleString(DEFAULT_LOCALE, { timeZone: zone })).getTime();
30
+ }
31
+ catch (err) {
32
+ }
33
+ if (!Number.isInteger(zone_time))
34
+ throw new Error(`format: Invalid zone passed - ${zone}`);
35
+ const offset = zone_time - client_time;
36
+ zone_offset_cache.set(ckey, offset);
37
+ return new Date(date.getTime() + offset);
38
+ }
39
+ function runIntl(loc, token, props, val) {
40
+ const hash = `${loc}:${token}`;
41
+ if (intl_formatters.has(hash))
42
+ return intl_formatters.get(hash).format(val);
43
+ try {
44
+ const instance = new Intl.DateTimeFormat(loc, props);
45
+ intl_formatters.set(hash, instance);
46
+ return instance.format(val);
47
+ }
48
+ catch (err) {
49
+ throw new Error(`format: Failed to run conversion for ${token} with locale ${loc}`);
50
+ }
51
+ }
52
+ const Tokens = [
53
+ ['YYYY', d => d.getFullYear()],
54
+ ['Q', d => ((d.getMonth() + 3) / 3) | 0],
55
+ ['MMMM', (d, loc) => runIntl(loc, 'MMMM', { month: 'long' }, d)],
56
+ ['MMM', (d, loc) => runIntl(loc, 'MMM', { month: 'short' }, d)],
57
+ ['MM', d => `${d.getMonth() + 1}`.padStart(2, '0')],
58
+ ['M', d => d.getMonth() + 1],
59
+ ['DD', d => `${d.getDate()}`.padStart(2, '0')],
60
+ ['D', d => d.getDate()],
61
+ ['dddd', (d, loc) => runIntl(loc, 'dddd', { weekday: 'long' }, d)],
62
+ ['ddd', (d, loc) => runIntl(loc, 'ddd', { weekday: 'short' }, d)],
63
+ ['HH', d => `${d.getHours()}`.padStart(2, '0')],
64
+ ['H', d => d.getHours()],
65
+ ['hh', d => `${((d.getHours() + 11) % 12) + 1}`.padStart(2, '0')],
66
+ ['h', d => ((d.getHours() + 11) % 12) + 1],
67
+ ['mm', d => `${d.getMinutes()}`.padStart(2, '0')],
68
+ ['m', d => d.getMinutes()],
69
+ ['ss', d => `${d.getSeconds()}`.padStart(2, '0')],
70
+ ['s', d => d.getSeconds()],
71
+ ['SSS', d => `${d.getMilliseconds()}`.padStart(3, '0')],
72
+ ['A', d => d.getHours() < 12 ? 'AM' : 'PM'],
73
+ ['a', d => d.getHours() < 12 ? 'am' : 'pm'],
74
+ ]
75
+ .sort((a, b) => a[0].length > b[0].length ? -1 : 1)
76
+ .map((el) => [el[0], new RegExp(el[0], 'g'), el[1]]);
77
+ function getSpecChain(spec) {
78
+ if (spec_cache.has(spec))
79
+ return spec_cache.get(spec);
80
+ const spec_chain = [];
81
+ let cursor;
82
+ for (let i = 0; i < Tokens.length; i++) {
83
+ cursor = Tokens[i];
84
+ if (spec.indexOf(cursor[0]) < 0)
85
+ continue;
86
+ spec_chain.push(cursor);
87
+ }
88
+ if (spec_chain.length === 0)
89
+ return false;
90
+ spec_cache.set(spec, spec_chain);
91
+ return spec_chain;
92
+ }
93
+ function format(val, spec, locale = DEFAULT_LOCALE, zone = DEFAULT_TZ) {
94
+ if (!(0, is_1.default)(val))
95
+ throw new TypeError('format: val must be a Date');
96
+ if (typeof spec !== 'string' || !spec.trim().length)
97
+ throw new TypeError('format: spec must be a non-empty string');
98
+ if (typeof locale !== 'string' || !locale.trim().length)
99
+ throw new TypeError('format: locale must be a non-empty string');
100
+ if (typeof zone !== 'string' || !zone.trim().length)
101
+ throw new TypeError('format: zone must be a non-empty string');
102
+ let formatted_string = spec;
103
+ const escaped_acc = [];
104
+ if (formatted_string.indexOf('[') >= 0) {
105
+ formatted_string = formatted_string.replace(escape_rgx, match => {
106
+ const escape_token = `$R${escaped_acc.length}$`;
107
+ escaped_acc.push([escape_token, match.replace('[', '').replace(']', '')]);
108
+ return escape_token;
109
+ });
110
+ }
111
+ const spec_chain = getSpecChain(formatted_string);
112
+ if (!spec_chain)
113
+ return val.toISOString();
114
+ const d = toZone(val, zone);
115
+ for (const el of spec_chain) {
116
+ formatted_string = formatted_string.replace(el[1], el[2](d, locale));
117
+ }
118
+ if (escaped_acc.length) {
119
+ for (const escape_token of escaped_acc) {
120
+ formatted_string = formatted_string.replace(escape_token[0], escape_token[1]);
121
+ }
122
+ }
123
+ return formatted_string;
124
+ }
125
+ exports.default = format;
package/date/is.js CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  function isDate(val) {
4
- return Object.prototype.toString.call(val) === '[object Date]' && !isNaN(val);
4
+ return val instanceof Date && !isNaN(val);
5
5
  }
6
6
  exports.default = isDate;
@@ -1,16 +1,16 @@
1
1
  'use strict';
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const is_1 = require("./is");
4
- const WEEK_START = {
5
- week: 1,
6
- week_sun: 0,
7
- week_mon: 1,
8
- week_tue: 2,
9
- week_wed: 3,
10
- week_thu: 4,
11
- week_fri: 5,
12
- week_sat: 6,
13
- };
4
+ const WEEK_START = new Map([
5
+ ['week', 1],
6
+ ['week_sun', 0],
7
+ ['week_mon', 1],
8
+ ['week_tue', 2],
9
+ ['week_wed', 3],
10
+ ['week_thu', 4],
11
+ ['week_fri', 5],
12
+ ['week_sat', 6],
13
+ ]);
14
14
  function startOfUTC(val, key = 'millisecond') {
15
15
  if (!(0, is_1.default)(val))
16
16
  throw new TypeError('startOfUTC requires a date object');
@@ -20,7 +20,8 @@ function startOfUTC(val, key = 'millisecond') {
20
20
  case 'year':
21
21
  return new Date(Date.UTC(val.getUTCFullYear(), 0, 1, 0, 0, 0, 0));
22
22
  case 'quarter': {
23
- return new Date(Date.UTC(val.getUTCFullYear(), val.getUTCMonth() - (val.getUTCMonth() % 3), 1, 0, 0, 0, 0));
23
+ const UTC_MONTH = val.getUTCMonth();
24
+ return new Date(Date.UTC(val.getUTCFullYear(), UTC_MONTH - (UTC_MONTH % 3), 1, 0, 0, 0, 0));
24
25
  }
25
26
  case 'month':
26
27
  return new Date(Date.UTC(val.getUTCFullYear(), val.getUTCMonth(), 1, 0, 0, 0, 0));
@@ -33,7 +34,7 @@ function startOfUTC(val, key = 'millisecond') {
33
34
  case 'week_fri':
34
35
  case 'week_sat': {
35
36
  const UTC_DAY = val.getUTCDay();
36
- const UTC_SOD = WEEK_START[key];
37
+ const UTC_SOD = WEEK_START.get(key);
37
38
  return new Date(Date.UTC(val.getUTCFullYear(), val.getUTCMonth(), val.getUTCDate() - (UTC_DAY < UTC_SOD ? (7 - UTC_SOD) + UTC_DAY : UTC_DAY - UTC_SOD), 0, 0, 0, 0));
38
39
  }
39
40
  case 'day':
@@ -44,7 +45,6 @@ function startOfUTC(val, key = 'millisecond') {
44
45
  return new Date(Date.UTC(val.getUTCFullYear(), val.getUTCMonth(), val.getUTCDate(), val.getUTCHours(), val.getUTCMinutes(), 0, 0));
45
46
  case 'second':
46
47
  return new Date(Date.UTC(val.getUTCFullYear(), val.getUTCMonth(), val.getUTCDate(), val.getUTCHours(), val.getUTCMinutes(), val.getUTCSeconds(), 0));
47
- case 'millisecond':
48
48
  default:
49
49
  return new Date(Date.UTC(val.getUTCFullYear(), val.getUTCMonth(), val.getUTCDate(), val.getUTCHours(), val.getUTCMinutes(), val.getUTCSeconds(), val.getUTCMilliseconds()));
50
50
  }
package/deep/get.js CHANGED
@@ -7,19 +7,19 @@ function deepGet(obj, path, get_parent = false) {
7
7
  if (typeof path !== 'string')
8
8
  throw new TypeError('No path was given');
9
9
  const path_s = path.trim();
10
- if (path_s.length === 0)
10
+ if (!path_s.length)
11
11
  throw new TypeError('No path was given');
12
12
  const parts = path_s
13
13
  .replace(/\[/g, '.')
14
14
  .replace(/(\.){2,}/g, '.')
15
15
  .replace(/(^\.|\.$|\])/g, '')
16
16
  .split('.');
17
- if (parts.length === 0 || (parts.length === 1 && get_parent))
17
+ if (!parts.length || (parts.length === 1 && get_parent))
18
18
  return obj;
19
19
  if (get_parent)
20
20
  parts.pop();
21
21
  let cursor = obj;
22
- while (parts.length > 0) {
22
+ while (parts.length) {
23
23
  if (Array.isArray(cursor)) {
24
24
  const ix = parseInt(parts.shift());
25
25
  if (!Number.isInteger(ix) || ix < 0 || ix > (cursor.length - 1))
@@ -33,7 +33,7 @@ function deepGet(obj, path, get_parent = false) {
33
33
  cursor = cursor[key];
34
34
  }
35
35
  if ((!Array.isArray(cursor) && Object.prototype.toString.call(cursor) !== '[object Object]') &&
36
- parts.length > 0)
36
+ parts.length)
37
37
  return undefined;
38
38
  }
39
39
  return cursor;
package/deep/set.js CHANGED
@@ -1,22 +1,24 @@
1
1
  'use strict';
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const RGX_MALICIOUS = /__proto__|constructor|prototype/;
3
4
  function deepSet(obj, path, value, define = false) {
4
5
  if (Object.prototype.toString.call(obj) !== '[object Object]' &&
5
6
  !Array.isArray(obj))
6
7
  throw new TypeError('Deepset is only supported for objects');
7
8
  if (typeof path !== 'string')
8
9
  throw new TypeError('No path was given');
9
- if (/__proto__|constructor|prototype/.test(path))
10
+ if (RGX_MALICIOUS.test(path))
10
11
  throw new TypeError('Malicious path provided');
11
12
  const path_s = path.trim();
12
- if (path_s.length === 0)
13
+ if (!path_s.length)
13
14
  throw new TypeError('No path was given');
14
15
  const parts = path_s
15
16
  .replace(/\[/g, '.')
16
17
  .replace(/(\.){2,}/g, '.')
17
18
  .replace(/(^\.|\.$|\])/g, '')
18
19
  .split('.');
19
- for (let i = 0; i < parts.length - 1; i++) {
20
+ const last_part_ix = parts.length - 1;
21
+ for (let i = 0; i < last_part_ix; i++) {
20
22
  if (parts[i] === '')
21
23
  continue;
22
24
  if (Array.isArray(obj)) {
@@ -36,16 +38,16 @@ function deepSet(obj, path, value, define = false) {
36
38
  if (!Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]')
37
39
  return false;
38
40
  if (define) {
39
- Object.defineProperty(obj, parts[parts.length - 1], value);
41
+ Object.defineProperty(obj, parts[last_part_ix], value);
40
42
  }
41
43
  else if (Array.isArray(obj)) {
42
- const idx = parseInt(parts[parts.length - 1]);
44
+ const idx = parseInt(parts[last_part_ix]);
43
45
  if (!Number.isInteger(idx) || idx < 0)
44
46
  throw new TypeError('Invalid path provided');
45
47
  obj[idx] = value;
46
48
  }
47
49
  else {
48
- obj[parts[parts.length - 1]] = value;
50
+ obj[parts[last_part_ix]] = value;
49
51
  }
50
52
  return true;
51
53
  }
package/equal.js CHANGED
@@ -23,21 +23,17 @@ function isObjectEqual(a, b) {
23
23
  return true;
24
24
  }
25
25
  function equal(a, b) {
26
- if (a instanceof Date &&
27
- b instanceof Date)
28
- return a.valueOf() === b.valueOf();
29
- if (Object.prototype.toString.call(a) === '[object RegExp]' &&
30
- Object.prototype.toString.call(b) === '[object RegExp]')
31
- return String(a) === String(b);
32
- if (Array.isArray(a) &&
33
- Array.isArray(b))
34
- return isArrayEqual(a, b);
35
- if (Object.prototype.toString.call(a) === '[object Object]' &&
36
- Object.prototype.toString.call(b) === '[object Object]')
37
- return isObjectEqual(a, b);
38
- if ((0, isNumericalNaN_1.default)(a)) {
39
- return (0, isNumericalNaN_1.default)(b);
26
+ if (a instanceof Date)
27
+ return b instanceof Date && a.valueOf() === b.valueOf();
28
+ if (a instanceof RegExp)
29
+ return b instanceof RegExp && String(a) === String(b);
30
+ if (Array.isArray(a))
31
+ return Array.isArray(b) && isArrayEqual(a, b);
32
+ if (Object.prototype.toString.call(a) === '[object Object]') {
33
+ return Object.prototype.toString.call(b) === '[object Object]' && isObjectEqual(a, b);
40
34
  }
35
+ if ((0, isNumericalNaN_1.default)(a))
36
+ return (0, isNumericalNaN_1.default)(b);
41
37
  return a === b;
42
38
  }
43
39
  exports.default = equal;
package/hash/fnv1A.js CHANGED
@@ -18,7 +18,7 @@ function fnv1A(data, offset = FNV_32) {
18
18
  else if (Array.isArray(data) || Object.prototype.toString.call(data) === '[object Object]') {
19
19
  sanitized = JSON.stringify(data);
20
20
  }
21
- else if (Object.prototype.toString.call(data) === '[object RegExp]') {
21
+ else if (data instanceof RegExp) {
22
22
  sanitized = data.toString();
23
23
  }
24
24
  else if (data instanceof Date) {
package/hash/guid.js CHANGED
@@ -1,33 +1,33 @@
1
1
  'use strict';
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const HEXMAP = [];
3
+ const HEX = [];
4
4
  for (let i = 0; i < 256; i++) {
5
- HEXMAP[i] = (i < 16 ? '0' : '') + i.toString(16);
5
+ HEX[i] = (i < 16 ? '0' : '') + i.toString(16);
6
6
  }
7
7
  function guid() {
8
8
  const d0 = (Math.random() * 0xffffffff) | 0;
9
9
  const d1 = (Math.random() * 0xffffffff) | 0;
10
10
  const d2 = (Math.random() * 0xffffffff) | 0;
11
11
  const d3 = (Math.random() * 0xffffffff) | 0;
12
- return HEXMAP[d0 & 0xff] +
13
- HEXMAP[(d0 >> 8) & 0xff] +
14
- HEXMAP[(d0 >> 16) & 0xff] +
15
- HEXMAP[(d0 >> 24) & 0xff] +
12
+ return HEX[d0 & 0xff] +
13
+ HEX[(d0 >> 8) & 0xff] +
14
+ HEX[(d0 >> 16) & 0xff] +
15
+ HEX[(d0 >> 24) & 0xff] +
16
16
  '-' +
17
- HEXMAP[d1 & 0xff] +
18
- HEXMAP[(d1 >> 8) & 0xff] +
17
+ HEX[d1 & 0xff] +
18
+ HEX[(d1 >> 8) & 0xff] +
19
19
  '-' +
20
- HEXMAP[((d1 >> 16) & 0x0f) | 0x40] +
21
- HEXMAP[(d1 >> 24) & 0xff] +
20
+ HEX[((d1 >> 16) & 0x0f) | 0x40] +
21
+ HEX[(d1 >> 24) & 0xff] +
22
22
  '-' +
23
- HEXMAP[(d2 & 0x3f) | 0x80] +
24
- HEXMAP[(d2 >> 8) & 0xff] +
23
+ HEX[(d2 & 0x3f) | 0x80] +
24
+ HEX[(d2 >> 8) & 0xff] +
25
25
  '-' +
26
- HEXMAP[(d2 >> 16) & 0xff] +
27
- HEXMAP[(d2 >> 24) & 0xff] +
28
- HEXMAP[d3 & 0xff] +
29
- HEXMAP[(d3 >> 8) & 0xff] +
30
- HEXMAP[(d3 >> 16) & 0xff] +
31
- HEXMAP[(d3 >> 24) & 0xff];
26
+ HEX[(d2 >> 16) & 0xff] +
27
+ HEX[(d2 >> 24) & 0xff] +
28
+ HEX[d3 & 0xff] +
29
+ HEX[(d3 >> 8) & 0xff] +
30
+ HEX[(d3 >> 16) & 0xff] +
31
+ HEX[(d3 >> 24) & 0xff];
32
32
  }
33
33
  exports.default = guid;
package/index.d.ts CHANGED
@@ -156,9 +156,6 @@ declare module "is" {
156
156
  }>;
157
157
  export default Is;
158
158
  }
159
- declare module "hash/fnv1A" {
160
- export default function fnv1A(data: unknown, offset?: number): number;
161
- }
162
159
  declare module "array/dedupe" {
163
160
  export default function dedupe<T>(val: T[]): T[];
164
161
  }
@@ -178,29 +175,18 @@ declare module "array/mapFn" {
178
175
  interface mapOptions {
179
176
  merge?: boolean;
180
177
  }
181
- interface kvMap {
182
- [key: string]: {
183
- [key: string]: any;
184
- };
185
- }
186
- export default function mapFn(arr: {
187
- [key: string]: any;
188
- }[], fn: (entry: {
178
+ type mapFn = (entry: {
189
179
  [key: string]: any;
190
- }) => (string | number | boolean), opts?: mapOptions): kvMap;
180
+ }) => (string | number | boolean);
181
+ type mapReturn = Record<string, Record<string, any>>;
182
+ export default function mapFn(arr: Record<string, any>[], fn: mapFn, opts?: mapOptions): mapReturn;
191
183
  }
192
184
  declare module "array/mapKey" {
193
185
  interface mapOptions {
194
186
  merge?: boolean;
195
187
  }
196
- interface kvMap {
197
- [key: string]: {
198
- [key: string]: any;
199
- };
200
- }
201
- export default function mapKey(arr: {
202
- [key: string]: any;
203
- }[], key: string, opts?: mapOptions): kvMap;
188
+ type kvMap = Record<string, Record<string, any>>;
189
+ export default function mapKey(arr: Record<string, any>[], key: string, opts?: mapOptions): kvMap;
204
190
  }
205
191
  declare module "array/mapPrimitive" {
206
192
  interface mapOptions {
@@ -208,9 +194,7 @@ declare module "array/mapPrimitive" {
208
194
  valround?: boolean | number;
209
195
  keyround?: boolean;
210
196
  }
211
- interface mapReturn {
212
- [key: string]: string | number;
213
- }
197
+ type mapReturn = Record<string, string | number>;
214
198
  export default function mapPrimitive(arr: unknown[], opts?: mapOptions): mapReturn;
215
199
  }
216
200
  declare module "array/shuffle" {
@@ -232,7 +216,7 @@ declare module "caching/memoize" {
232
216
  export default function memoize(fn: Function, resolver?: Function): Function;
233
217
  }
234
218
  declare module "date/addUTC" {
235
- export default function addUTC(val: Date, amount?: number, key?: 'years' | 'year' | 'months' | 'month' | 'days' | 'day' | 'hours' | 'hour' | 'minutes' | 'minute' | 'seconds' | 'second' | 'milliseconds' | 'millisecond'): Date;
219
+ export default function addUTC(val: Date, amt?: number, key?: 'years' | 'year' | 'months' | 'month' | 'days' | 'day' | 'hours' | 'hour' | 'minutes' | 'minute' | 'seconds' | 'second' | 'milliseconds' | 'millisecond'): Date;
236
220
  }
237
221
  declare module "date/diff" {
238
222
  export default function diff(val_a: Date, val_b: Date, key?: 'week' | 'weeks' | 'day' | 'days' | 'hour' | 'hours' | 'minute' | 'minutes' | 'second' | 'seconds' | 'millisecond' | 'milliseconds'): number;
@@ -240,6 +224,9 @@ declare module "date/diff" {
240
224
  declare module "date/endOfUTC" {
241
225
  export default function endOfUTC(val: Date, key?: 'year' | 'quarter' | 'month' | 'week' | 'week_sun' | 'week_mon' | 'week_tue' | 'week_wed' | 'week_thu' | 'week_fri' | 'week_sat' | 'day' | 'hour' | 'minute' | 'second' | 'millisecond'): Date;
242
226
  }
227
+ declare module "date/format" {
228
+ export default function format(val: Date, spec: string, locale?: string, zone?: string): string;
229
+ }
243
230
  declare module "date/nowUnix" {
244
231
  export default function nowUnix(): number;
245
232
  }
@@ -303,6 +290,9 @@ declare module "function/noopreturn" {
303
290
  declare module "function/sleep" {
304
291
  export default function sleep(ms?: number): Promise<void>;
305
292
  }
293
+ declare module "hash/fnv1A" {
294
+ export default function fnv1A(data: unknown, offset?: number): number;
295
+ }
306
296
  declare module "hash/guid" {
307
297
  export default function guid(): string;
308
298
  }
@@ -353,7 +343,7 @@ declare module "string/humanizeNumber" {
353
343
  divider?: number;
354
344
  real?: boolean;
355
345
  }
356
- export default function humanizeNumber(val: number | string, options?: humanizeNumberOptions): string;
346
+ export default function humanizeNumber(val: number | string, options?: humanizeNumberOptions | false): string;
357
347
  }
358
348
  declare module "string/humanizeBytes" {
359
349
  interface humanizeBytesOptions {
package/object/pick.js CHANGED
@@ -2,10 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const get_1 = require("../deep/get");
4
4
  const set_1 = require("../deep/set");
5
+ const RGX_DEEP = /(\.|\[)/;
5
6
  function pick(obj, keys) {
6
7
  if (Object.prototype.toString.call(obj) !== '[object Object]' ||
7
8
  !Array.isArray(keys) ||
8
- keys.length === 0)
9
+ !keys.length)
9
10
  throw new TypeError('Please pass an object to pick from and a keys array');
10
11
  const map = {};
11
12
  let val;
@@ -14,9 +15,9 @@ function pick(obj, keys) {
14
15
  if (typeof key !== 'string')
15
16
  continue;
16
17
  sanitized = key.trim();
17
- if (sanitized.length === 0)
18
+ if (!sanitized.length)
18
19
  continue;
19
- if (/(\.|\[)/g.test(sanitized)) {
20
+ if (RGX_DEEP.test(sanitized)) {
20
21
  val = (0, get_1.default)(obj, sanitized);
21
22
  if (val === undefined)
22
23
  continue;
package/package.json CHANGED
@@ -1 +1 @@
1
- { "name": "@valkyriestudios/utils", "version": "11.7.0", "description": "A collection of single-function utilities for common tasks", "author": { "name": "Peter Vermeulen", "email": "contact@valkyriestudios.be", "url": "www.valkyriestudios.be" }, "keywords": [ "utility", "library", "javascript", "js", "node", "bun" ], "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/ValkyrieStudios/utils.git" }, "bugs": { "url": "https://github.com/ValkyrieStudios/utils/issues" }, "homepage": "https://github.com/ValkyrieStudios/utils#readme", "types": "index.d.ts" }
1
+ { "name": "@valkyriestudios/utils", "version": "12.1.0", "description": "A collection of single-function utilities for common tasks", "author": { "name": "Peter Vermeulen", "email": "contact@valkyriestudios.be", "url": "www.valkyriestudios.be" }, "keywords": [ "utility", "library", "javascript", "js", "node", "bun" ], "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/ValkyrieStudios/utils.git" }, "bugs": { "url": "https://github.com/ValkyrieStudios/utils/issues" }, "homepage": "https://github.com/ValkyrieStudios/utils#readme", "types": "index.d.ts" }
package/regexp/is.js CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  function isRegExp(val) {
4
- return Object.prototype.toString.call(val) === '[object RegExp]';
4
+ return val instanceof RegExp;
5
5
  }
6
6
  exports.default = isRegExp;
@@ -8,13 +8,13 @@ function humanizeBytes(val, options = {}) {
8
8
  delim: has_opts && typeof options.delim === 'string'
9
9
  ? options.delim
10
10
  : ',',
11
- separator: has_opts && typeof options.separator === 'string' && options.separator.trim().length > 0
11
+ separator: has_opts && typeof options.separator === 'string' && options.separator.trim().length
12
12
  ? options.separator
13
13
  : '.',
14
14
  precision: has_opts && Number.isInteger(options.precision) && options.precision >= 0
15
15
  ? options.precision
16
16
  : 2,
17
- units: has_opts && Array.isArray(options.units) && options.units.length > 0
17
+ units: has_opts && Array.isArray(options.units) && options.units.length
18
18
  ? options.units.filter(el => (0, isNotEmpty_1.default)(el))
19
19
  : [' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB'],
20
20
  divider: 1024,
@@ -48,5 +48,5 @@ interface humanizeNumberOptions {
48
48
  *
49
49
  * @returns Humanized number as string
50
50
  */
51
- export default function humanizeNumber(val: number | string, options?: humanizeNumberOptions): string;
51
+ export default function humanizeNumber(val: number | string, options?: humanizeNumberOptions | false): string;
52
52
  export {};
@@ -1,60 +1,56 @@
1
1
  'use strict';
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const is_1 = require("../boolean/is");
4
- const is_2 = require("../string/is");
5
3
  const round_1 = require("../number/round");
6
- function humanizeNumber(val, options = {}) {
7
- const has_opts = Object.prototype.toString.call(options) === '[object Object]';
8
- const OPTS = {
9
- delim: has_opts && typeof options.delim === 'string'
10
- ? options.delim
11
- : ',',
12
- separator: has_opts && typeof options.separator === 'string' && options.separator.trim().length > 0
13
- ? options.separator
14
- : '.',
15
- precision: has_opts && Number.isInteger(options.precision) && options.precision >= 0
16
- ? options.precision
17
- : 2,
18
- units: has_opts && ((Array.isArray(options.units) && options.units.length > 0) || options.units === false)
19
- ? options.units ? options.units.filter(is_2.default) : false
20
- : ['', 'k', 'm', 'b', 't', 'q'],
21
- divider: has_opts && Number.isInteger(options.divider) && options.divider > 1
22
- ? options.divider
23
- : 1000,
24
- real: has_opts && (0, is_1.default)(options.real)
25
- ? options.real
26
- : false,
27
- };
28
- let normalized;
29
- if (OPTS.real) {
30
- normalized = typeof val === 'string' ? parseInt(val.trim(), 10) : Number.isFinite(val) ? Math.round(val) : 0;
4
+ const DEFAULT_UNITS = ['', 'k', 'm', 'b', 't', 'q'];
5
+ function humanizeNumber(val, options = false) {
6
+ let DELIM = ',';
7
+ let SEPARATOR = '.';
8
+ let PRECISION = 2;
9
+ let UNITS = DEFAULT_UNITS;
10
+ let DIVIDER = 1000;
11
+ let REAL = false;
12
+ if (options && Object.prototype.toString.call(options) === '[object Object]') {
13
+ if (typeof options.delim === 'string')
14
+ DELIM = options.delim;
15
+ if (typeof options.separator === 'string' && options.separator.trim().length)
16
+ SEPARATOR = options.separator;
17
+ if (Number.isInteger(options.precision) && options.precision >= 0)
18
+ PRECISION = options.precision;
19
+ if (Array.isArray(options.units) && options.units.length) {
20
+ UNITS = options.units;
21
+ }
22
+ else if (options.units === false) {
23
+ UNITS = false;
24
+ }
25
+ if (Number.isInteger(options.divider) && options.divider > 1) {
26
+ DIVIDER = options.divider;
27
+ }
28
+ if (options.real === true)
29
+ REAL = true;
31
30
  }
32
- else {
33
- normalized = typeof val === 'string' ? parseFloat(val) : Number.isFinite(val) ? val : 0;
31
+ let normalized = 0;
32
+ if (typeof val === 'string') {
33
+ normalized = REAL ? parseInt(val.trim(), 10) : parseFloat(val);
34
34
  }
35
- if (!Number.isFinite(normalized) || normalized === 0) {
36
- return `0${Array.isArray(OPTS.units) && OPTS.units.length > 0 ? OPTS.units[0] : ''}`;
35
+ else if (Number.isFinite(val)) {
36
+ normalized = REAL ? Math.round(val) : val;
37
37
  }
38
+ if (!Number.isFinite(normalized) || normalized === 0)
39
+ return UNITS ? `0${UNITS[0]}` : '0';
38
40
  const sign = normalized < 0 ? '-' : '';
39
41
  normalized = Math.abs(normalized);
40
- let postfix = '';
41
- if (Array.isArray(OPTS.units) && OPTS.units.length > 0) {
42
- let unit_ix = 0;
43
- while (normalized >= OPTS.divider) {
44
- unit_ix++;
45
- normalized = normalized / OPTS.divider;
46
- if (unit_ix === OPTS.units.length - 1)
47
- break;
42
+ let unit_ix = 0;
43
+ if (UNITS) {
44
+ for (unit_ix; normalized >= DIVIDER && unit_ix < UNITS.length - 1; unit_ix++) {
45
+ normalized /= DIVIDER;
48
46
  }
49
- postfix = OPTS.units[unit_ix];
50
47
  }
51
- normalized = (0, round_1.default)(normalized, OPTS.precision);
52
- const humanized = `${normalized}`.split('.');
48
+ const humanized = `${(0, round_1.default)(normalized, PRECISION)}`.split('.', 2);
53
49
  humanized[0] = humanized[0].split('').reverse().map((char, ix, original) => {
54
50
  if (ix > 0 && ix < original.length && ix % 3 === 0)
55
- return char + OPTS.delim;
51
+ return char + DELIM;
56
52
  return char;
57
53
  }).reverse().join('');
58
- return `${sign}${humanized.join(OPTS.separator)}${postfix}`;
54
+ return `${sign}${humanized.join(SEPARATOR)}${UNITS ? UNITS[unit_ix] : ''}`;
59
55
  }
60
56
  exports.default = humanizeNumber;
package/string/shorten.js CHANGED
@@ -3,9 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  function shorten(val, length, postfix = '...') {
4
4
  if (typeof val !== 'string')
5
5
  return '';
6
- if (typeof postfix !== 'string' || !Number.isFinite(length) || length <= 0)
6
+ if (typeof postfix !== 'string' || !Number.isInteger(length) || length <= 0)
7
7
  return val;
8
8
  const sanitized = val.trim();
9
- return sanitized.length <= length ? sanitized : `${sanitized.substr(0, length)}${postfix}`;
9
+ return sanitized.length <= length ? sanitized : `${sanitized.substring(0, length)}${postfix}`;
10
10
  }
11
11
  exports.default = shorten;