@nativerent/js-utils 1.2.2 → 1.2.4

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/dist/index.js CHANGED
@@ -1,675 +1,621 @@
1
- export function debounce(fn, delay) {
2
- let timeout;
3
- return function (...args) {
4
- clearTimeout(timeout);
5
- timeout = setTimeout(() => fn.apply(null, args), delay);
6
- };
7
- }
8
- export function throttle(fn, delay) {
9
- let lastCall = 0;
10
- return function (...args) {
11
- const now = new Date().getTime();
12
- if (now - lastCall < delay) {
13
- return;
14
- }
15
- lastCall = now;
16
- fn(...args);
17
- };
18
- }
19
- export function isObject(value) {
20
- return !!value && typeof value === "object" && !Array.isArray(value);
21
- }
22
- export function isFn(value) {
23
- return typeof value === "function";
24
- }
25
- export function isStr(value) {
26
- return typeof value === "string";
27
- }
28
- export function isString(value) {
29
- return typeof value === "string";
30
- }
31
- /**
32
- * Check if the given argument is a string which is not empty
33
- */
34
- export function isNotEmptyString(value) {
35
- return isString(value) && value.length > 0;
36
- }
37
- export function isHTMLElement(value) {
38
- return value instanceof HTMLElement || value instanceof SVGElement;
39
- }
40
- export function isNum(value) {
41
- return typeof value === "number";
42
- }
43
- export function isBool(value) {
44
- return typeof value === "boolean";
45
- }
46
- export function isUndef(value) {
47
- return typeof value === "undefined";
48
- }
49
- export function isNullOrUndef(value) {
50
- return value === null || typeof value === "undefined";
51
- }
52
- export function isDefined(value) {
53
- return !isUndef(value);
54
- }
55
- /**
56
- * Returns an array containing all the elements of array1 that are not in array2 and vice-versa
57
- */
58
- export function arrayDiff(array1, array2) {
59
- return array1
60
- .filter((value) => !array2.includes(value))
61
- .concat(array2.filter((value) => !array1.includes(value)));
62
- }
63
- /**
64
- * Returns an array of elements present in array1 and array2
65
- */
66
- export function arrayIntersect(array1, array2) {
67
- const set = new Set(array2);
68
- return array1.filter((value) => set.has(value));
69
- }
70
- export function deepCloneObject(object) {
71
- return JSON.parse(JSON.stringify(object));
72
- }
73
- // todo: non-px values
74
- export function getNumericStyleProp(prop, el) {
75
- const styles = window.getComputedStyle(el);
76
- return !isNullOrUndef(styles[prop]) ? parseFloat(styles[prop] || 0) : 0;
77
- }
78
- export function objectHasProp(obj, prop) {
79
- return Object.prototype.hasOwnProperty.call(obj, prop);
80
- }
81
- /**
82
- * Custom version of Object.keys()
83
- */
84
- export function getObjectKeys(object) {
85
- let key;
86
- let keys = [];
87
- for (key in object) {
88
- if (Object.prototype.hasOwnProperty.call(object, key)) {
89
- keys.push(key);
90
- }
91
- }
92
- return keys;
93
- }
94
- /**
95
- * Convert an object to a query string
96
- * Works with primitive objects
97
- */
98
- export function objectToQueryString(object) {
99
- return Object.entries(object)
100
- .map(([k, v]) => {
101
- if (Array.isArray(v)) {
102
- return v
103
- .map((item) => `${k}[]=${encodeURIComponent(item || "")}`)
104
- .join("&");
105
- }
106
- else if (isObject(v)) {
107
- return `${k}=${encodeURIComponent(JSON.stringify(v))}`;
108
- }
109
- return `${k}=${encodeURIComponent(v || "")}`;
110
- })
111
- .join("&");
112
- }
113
- export function countObjectInnerLength(object) {
114
- return Object.values(object).reduce((sum, arr) => sum + (arr?.length ?? 0), 0);
115
- }
116
- /**
117
- * Check if the element is in viewport
118
- */
119
- export function isElementVisible(element, minVisiblePercent = 50) {
120
- const { top, bottom, height } = element.getBoundingClientRect();
121
- if (!height)
122
- return false;
123
- const viewportTop = 0;
124
- const viewportBottom = window.innerHeight;
125
- const visibleTop = Math.max(top, viewportTop);
126
- const visibleBottom = Math.min(bottom, viewportBottom);
127
- const visibleHeight = Math.max(0, visibleBottom - visibleTop);
128
- return (visibleHeight / height) * 100 >= minVisiblePercent;
129
- }
130
- export function decodeSafeURL(url) {
131
- try {
132
- return decodeURI(url);
133
- }
134
- catch {
135
- return url;
1
+ 'use strict';
2
+
3
+ function debounce(fn, delay) {
4
+ let timeout;
5
+ return function(...args) {
6
+ clearTimeout(timeout);
7
+ timeout = setTimeout(() => fn.apply(null, args), delay);
8
+ };
9
+ }
10
+ function throttle(fn, delay) {
11
+ let lastCall = 0;
12
+ return function(...args) {
13
+ const now = (/* @__PURE__ */ new Date()).getTime();
14
+ if (now - lastCall < delay) {
15
+ return;
136
16
  }
17
+ lastCall = now;
18
+ fn(...args);
19
+ };
137
20
  }
138
- export function getSafeURL(url) {
139
- url = url ? url : location.href;
140
- return encodeURI(decodeSafeURL(url));
21
+ function isObject(value) {
22
+ return !!value && typeof value === "object" && !Array.isArray(value);
141
23
  }
142
- export function parseURL(url) {
143
- return new URL(url);
24
+ function isFn(value) {
25
+ return typeof value === "function";
144
26
  }
145
- export function encodeQueryString(url) {
146
- if (url.length > 0) {
147
- const index = url.indexOf("?");
148
- if (index >= 0) {
149
- return url.substring(0, index) + parseURL(url).search;
150
- }
151
- }
152
- return url;
27
+ function isStr(value) {
28
+ return typeof value === "string";
153
29
  }
154
- export function injectScript(filename) {
155
- const script = document.createElement("script");
156
- script.src = filename;
157
- script.async = true;
158
- document.head.appendChild(script);
159
- }
160
- export function injectStyleLink(filename) {
161
- const link = document.createElement("link");
162
- link.rel = "stylesheet";
163
- link.href = filename;
164
- document.head.appendChild(link);
165
- }
166
- export function toBinaryStr(str) {
167
- const CHUNK = 0x8000; // String.fromCharCode(...charCodes) can overflow the call stack with large strings
168
- const bytes = new TextEncoder().encode(str);
169
- let result = "";
170
- for (let i = 0; i < bytes.length; i += CHUNK) {
171
- result += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
172
- }
173
- return result;
174
- }
175
- /**
176
- * Find a DOM element where an ad unit should be rendered to
177
- */
178
- export function getHtmlElement(id) {
179
- return document.getElementById(id);
180
- }
181
- /**
182
- * Convert an HTML string into a list of nodes
183
- */
184
- export function stringToHtmlElements(html) {
185
- const template = createHtmlElement("div");
186
- template.innerHTML = html.replace(/[\r\n]/gm, "").trim();
187
- return template.childNodes;
188
- }
189
- /**
190
- * Creates an HTML element and sets attributes
191
- */
192
- export function createHtmlElement(type, attributes = {}) {
193
- const el = document.createElement(type);
194
- for (const [k, v] of Object.entries(attributes))
195
- el.setAttribute(k, v);
196
- return el;
197
- }
198
- /**
199
- * Insert HTML elements into DOM
200
- */
201
- export function insertHtmlElements(nodes, appendTo = document.body) {
202
- const fragment = document.createDocumentFragment();
203
- for (let i = 0; i < nodes.length; i++) {
204
- const node = nodes[i];
205
- // Allow elements + text nodes only
206
- if (!isHTMLElement(node) && node?.nodeType !== Node.TEXT_NODE) {
207
- continue;
208
- }
209
- let newNode;
210
- // Text node
211
- if (node?.nodeType === Node.TEXT_NODE) {
212
- newNode = document.createTextNode(node.textContent ?? "");
213
- fragment.appendChild(newNode);
214
- continue;
215
- }
216
- // Element node from here on
217
- const el = node;
218
- const tag = el.tagName.toLowerCase();
219
- switch (tag) {
220
- case "script": {
221
- const src = el.getAttribute("src");
222
- newNode =
223
- !isNullOrUndef(src) && src.length > 0
224
- ? createScriptElement(src, false, flatHtmlAttributes(el.attributes))
225
- : createScriptElement(el.textContent ?? "", true, flatHtmlAttributes(el.attributes));
226
- break;
227
- }
228
- case "style":
229
- newNode = createStyleElement(el.textContent);
230
- break;
231
- case "svg":
232
- newNode = createSvgElement(el.innerHTML, flatHtmlAttributes(el.attributes));
233
- break;
234
- default: {
235
- const created = createHtmlElement(el.tagName, flatHtmlAttributes(el.attributes));
236
- // Recurse for children (handles mixed element/text)
237
- if (el.childNodes.length) {
238
- insertHtmlElements(el.childNodes, created);
239
- }
240
- else {
241
- created.textContent = el.textContent ?? "";
242
- }
243
- newNode = created;
244
- }
245
- }
246
- fragment.appendChild(newNode);
247
- }
248
- appendTo.appendChild(fragment);
249
- }
250
- /**
251
- * Make a simple object which contains only attribute name and value
252
- */
253
- export function flatHtmlAttributes(attributes) {
254
- if (!attributes)
255
- return {};
256
- const result = {};
257
- for (let i = 0; i < attributes.length; i++) {
258
- const attr = attributes[i];
259
- if (attr) {
260
- result[attr.name] = attr.value;
261
- }
262
- }
263
- return result;
264
- }
265
- /**
266
- * Create a <script> element
267
- */
268
- export function createScriptElement(js, inline = false, attributes = {}) {
269
- const el = document.createElement("script");
270
- for (const [k, v] of Object.entries(attributes)) {
271
- el.setAttribute(k, v);
272
- }
273
- if (inline) {
274
- el.appendChild(document.createTextNode(js));
275
- }
276
- else {
277
- el.async = true;
278
- el.src = js;
30
+ function isString(value) {
31
+ return typeof value === "string";
32
+ }
33
+ function isNotEmptyString(value) {
34
+ return isString(value) && value.length > 0;
35
+ }
36
+ function isHTMLElement(value) {
37
+ return value instanceof HTMLElement || value instanceof SVGElement;
38
+ }
39
+ function isNum(value) {
40
+ return typeof value === "number";
41
+ }
42
+ function isBool(value) {
43
+ return typeof value === "boolean";
44
+ }
45
+ function isUndef(value) {
46
+ return typeof value === "undefined";
47
+ }
48
+ function isNullOrUndef(value) {
49
+ return value === null || typeof value === "undefined";
50
+ }
51
+ function isDefined(value) {
52
+ return !isUndef(value);
53
+ }
54
+ function arrayDiff(array1, array2) {
55
+ return array1.filter((value) => !array2.includes(value)).concat(array2.filter((value) => !array1.includes(value)));
56
+ }
57
+ function arrayIntersect(array1, array2) {
58
+ const set = new Set(array2);
59
+ return array1.filter((value) => set.has(value));
60
+ }
61
+ function deepCloneObject(object) {
62
+ return JSON.parse(JSON.stringify(object));
63
+ }
64
+ function getNumericStyleProp(prop, el) {
65
+ const styles = window.getComputedStyle(el);
66
+ return !isNullOrUndef(styles[prop]) ? parseFloat(styles[prop] || 0) : 0;
67
+ }
68
+ function objectHasProp(obj, prop) {
69
+ return Object.prototype.hasOwnProperty.call(obj, prop);
70
+ }
71
+ function getObjectKeys(object) {
72
+ let key;
73
+ let keys = [];
74
+ for (key in object) {
75
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
76
+ keys.push(key);
279
77
  }
280
- return el;
281
- }
282
- /**
283
- * Create a <style> element
284
- */
285
- export function createStyleElement(css) {
286
- const element = createHtmlElement("style");
287
- if (css) {
288
- element.appendChild(document.createTextNode(css));
78
+ }
79
+ return keys;
80
+ }
81
+ function objectToQueryString(object) {
82
+ return Object.entries(object).map(([k, v]) => {
83
+ if (Array.isArray(v)) {
84
+ return v.map((item) => `${k}[]=${encodeURIComponent(item || "")}`).join("&");
85
+ } else if (isObject(v)) {
86
+ return `${k}=${encodeURIComponent(JSON.stringify(v))}`;
289
87
  }
290
- return element;
291
- }
292
- /**
293
- * Create a <link> element
294
- */
295
- export function createLinkElement(href) {
296
- const element = createHtmlElement("link");
297
- element.rel = "stylesheet";
298
- element.href = href;
299
- return element;
300
- }
301
- /**
302
- * Create svg elements
303
- */
304
- export function createSvgElement(content, attributes = {}) {
305
- const element = document.createElementNS("http://www.w3.org/2000/svg", "svg");
306
- for (const [name, value] of Object.entries(attributes)) {
307
- element.setAttribute(name, value);
88
+ return `${k}=${encodeURIComponent(v || "")}`;
89
+ }).join("&");
90
+ }
91
+ function countObjectInnerLength(object) {
92
+ return Object.values(object).reduce(
93
+ (sum, arr) => sum + (arr?.length ?? 0),
94
+ 0
95
+ );
96
+ }
97
+ function isElementVisible(element, minVisiblePercent = 50) {
98
+ const { top, bottom, height } = element.getBoundingClientRect();
99
+ if (!height) return false;
100
+ const viewportTop = 0;
101
+ const viewportBottom = window.innerHeight;
102
+ const visibleTop = Math.max(top, viewportTop);
103
+ const visibleBottom = Math.min(bottom, viewportBottom);
104
+ const visibleHeight = Math.max(0, visibleBottom - visibleTop);
105
+ return visibleHeight / height * 100 >= minVisiblePercent;
106
+ }
107
+ function decodeSafeURL(url) {
108
+ try {
109
+ return decodeURI(url);
110
+ } catch {
111
+ return url;
112
+ }
113
+ }
114
+ function getSafeURL(url) {
115
+ url = url ? url : location.href;
116
+ return encodeURI(decodeSafeURL(url));
117
+ }
118
+ function parseURL(url) {
119
+ return new URL(url);
120
+ }
121
+ function encodeQueryString(url) {
122
+ if (url.length > 0) {
123
+ const index = url.indexOf("?");
124
+ if (index >= 0) {
125
+ return url.substring(0, index) + parseURL(url).search;
308
126
  }
309
- element.innerHTML = content.trim();
310
- return element;
311
- }
312
- /**
313
- * Create an image element to use as a tracking pixel
314
- */
315
- export function createPixelElement(src) {
316
- const image = document.createElement("img");
317
- image.alt = "";
318
- image.src = src;
319
- image.width = 1;
320
- image.height = 1;
321
- image.loading = "eager";
322
- image.setAttribute("aria-hidden", "true");
323
- image.style.position = "absolute";
324
- image.style.left = "-99999px";
325
- return image;
326
- }
327
- /**
328
- * Append a new script element to the DOM head
329
- */
330
- export function insertJs(js, inline = false) {
331
- const element = createScriptElement(js, inline);
332
- document.head.appendChild(element);
333
- }
334
- /**
335
- * Append a new style element to the DOM head
336
- */
337
- export function insertCss(css, className, external = false) {
338
- const element = external ? createLinkElement(css) : createStyleElement(css);
339
- if (className) {
340
- element.className = className;
127
+ }
128
+ return url;
129
+ }
130
+ function injectScript(filename) {
131
+ const script = document.createElement("script");
132
+ script.src = filename;
133
+ script.async = true;
134
+ document.head.appendChild(script);
135
+ }
136
+ function injectStyleLink(filename) {
137
+ const link = document.createElement("link");
138
+ link.rel = "stylesheet";
139
+ link.href = filename;
140
+ document.head.appendChild(link);
141
+ }
142
+ function toBinaryStr(str) {
143
+ const CHUNK = 32768;
144
+ const bytes = new TextEncoder().encode(str);
145
+ let result = "";
146
+ for (let i = 0; i < bytes.length; i += CHUNK) {
147
+ result += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
148
+ }
149
+ return result;
150
+ }
151
+ function getHtmlElement(id) {
152
+ return document.getElementById(id);
153
+ }
154
+ function stringToHtmlElements(html) {
155
+ const template = createHtmlElement("div");
156
+ template.innerHTML = html.replace(/[\r\n]/gm, "").trim();
157
+ return template.childNodes;
158
+ }
159
+ function createHtmlElement(type, attributes = {}) {
160
+ const el = document.createElement(type);
161
+ for (const [k, v] of Object.entries(attributes)) el.setAttribute(k, v);
162
+ return el;
163
+ }
164
+ function insertHtmlElements(nodes, appendTo = document.body) {
165
+ const fragment = document.createDocumentFragment();
166
+ for (let i = 0; i < nodes.length; i++) {
167
+ const node = nodes[i];
168
+ if (!node || !isHTMLElement(node) && node.nodeType !== Node.TEXT_NODE) {
169
+ continue;
341
170
  }
342
- document.head.appendChild(element);
343
- }
344
- /**
345
- * Get screen sizes
346
- */
347
- export function getScreenSize() {
348
- const width = window.screen?.width ?? window.innerWidth;
349
- const height = window.screen?.height ?? window.innerHeight;
350
- return { width, height };
351
- }
352
- /**
353
- * Get a random integer between min and max
354
- */
355
- export function getRandomInt(min = 0, max = 4294967295) {
356
- min = Math.ceil(min);
357
- max = Math.floor(max);
358
- if (max <= min) {
359
- return min;
171
+ let newNode;
172
+ if (node.nodeType === Node.TEXT_NODE) {
173
+ newNode = document.createTextNode(node.textContent ?? "");
174
+ fragment.appendChild(newNode);
175
+ continue;
360
176
  }
361
- return Math.floor(Math.random() * (max - min)) + min;
362
- }
363
- /**
364
- * Implementation of Java's String.hashCode() method
365
- */
366
- export function hashCode(str) {
367
- let hash = 0, chr;
368
- for (let i = 0; i < str.length; i++) {
369
- chr = str.charCodeAt(i);
370
- hash = (hash << 5) - hash + chr;
371
- hash |= 0; // convert to 32bit integer
177
+ const el = node;
178
+ const tag = el.tagName.toLowerCase();
179
+ switch (tag) {
180
+ case "script": {
181
+ const src = el.getAttribute("src");
182
+ newNode = !isNullOrUndef(src) && src.length > 0 ? createScriptElement(src, false, flatHtmlAttributes(el.attributes)) : createScriptElement(
183
+ el.textContent ?? "",
184
+ true,
185
+ flatHtmlAttributes(el.attributes)
186
+ );
187
+ break;
188
+ }
189
+ case "style":
190
+ newNode = createStyleElement(el.textContent);
191
+ break;
192
+ case "svg":
193
+ newNode = createSvgElement(
194
+ el.innerHTML,
195
+ flatHtmlAttributes(el.attributes)
196
+ );
197
+ break;
198
+ default: {
199
+ const created = createHtmlElement(
200
+ el.tagName,
201
+ flatHtmlAttributes(el.attributes)
202
+ );
203
+ if (el.childNodes.length) {
204
+ insertHtmlElements(el.childNodes, created);
205
+ } else {
206
+ created.textContent = el.textContent ?? "";
207
+ }
208
+ newNode = created;
209
+ }
372
210
  }
373
- return hash >>> 0;
374
- }
375
- /**
376
- * Executes a callback as soon as DOM is interactive
377
- */
378
- export function onDOMReady(callback, ...args) {
379
- if (document.readyState === "interactive" ||
380
- document.readyState === "complete") {
381
- callback(...args);
211
+ fragment.appendChild(newNode);
212
+ }
213
+ appendTo.appendChild(fragment);
214
+ }
215
+ function flatHtmlAttributes(attributes) {
216
+ if (!attributes) return {};
217
+ const result = {};
218
+ for (let i = 0; i < attributes.length; i++) {
219
+ const attr = attributes[i];
220
+ if (attr) {
221
+ result[attr.name] = attr.value;
382
222
  }
383
- else {
384
- document.addEventListener("DOMContentLoaded", () => callback(...args));
223
+ }
224
+ return result;
225
+ }
226
+ function createScriptElement(js, inline = false, attributes = {}) {
227
+ const el = document.createElement("script");
228
+ for (const [k, v] of Object.entries(attributes)) {
229
+ el.setAttribute(k, v);
230
+ }
231
+ if (inline) {
232
+ el.appendChild(document.createTextNode(js));
233
+ } else {
234
+ el.async = true;
235
+ el.src = js;
236
+ }
237
+ return el;
238
+ }
239
+ function createStyleElement(css) {
240
+ const element = createHtmlElement("style");
241
+ if (css) {
242
+ element.appendChild(document.createTextNode(css));
243
+ }
244
+ return element;
245
+ }
246
+ function createLinkElement(href) {
247
+ const element = createHtmlElement("link");
248
+ element.rel = "stylesheet";
249
+ element.href = href;
250
+ return element;
251
+ }
252
+ function createSvgElement(content, attributes = {}) {
253
+ const element = document.createElementNS(
254
+ "http://www.w3.org/2000/svg",
255
+ "svg"
256
+ );
257
+ for (const [name, value] of Object.entries(attributes)) {
258
+ element.setAttribute(name, value);
259
+ }
260
+ element.innerHTML = content.trim();
261
+ return element;
262
+ }
263
+ function createPixelElement(src) {
264
+ const image = document.createElement("img");
265
+ image.alt = "";
266
+ image.src = src;
267
+ image.width = 1;
268
+ image.height = 1;
269
+ image.loading = "eager";
270
+ image.setAttribute("aria-hidden", "true");
271
+ image.style.position = "absolute";
272
+ image.style.left = "-99999px";
273
+ return image;
274
+ }
275
+ function insertJs(js, inline = false) {
276
+ const element = createScriptElement(js, inline);
277
+ document.head.appendChild(element);
278
+ }
279
+ function insertCss(css, className, external = false) {
280
+ const element = external ? createLinkElement(css) : createStyleElement(css);
281
+ if (className) {
282
+ element.className = className;
283
+ }
284
+ document.head.appendChild(element);
285
+ }
286
+ function getScreenSize() {
287
+ const width = window.screen?.width ?? window.innerWidth;
288
+ const height = window.screen?.height ?? window.innerHeight;
289
+ return { width, height };
290
+ }
291
+ function getRandomInt(min = 0, max = 4294967295) {
292
+ min = Math.ceil(min);
293
+ max = Math.floor(max);
294
+ if (max <= min) {
295
+ return min;
296
+ }
297
+ return Math.floor(Math.random() * (max - min)) + min;
298
+ }
299
+ function hashCode(str) {
300
+ let hash = 0, chr;
301
+ for (let i = 0; i < str.length; i++) {
302
+ chr = str.charCodeAt(i);
303
+ hash = (hash << 5) - hash + chr;
304
+ hash |= 0;
305
+ }
306
+ return hash >>> 0;
307
+ }
308
+ function onDOMReady(callback, ...args) {
309
+ if (document.readyState === "interactive" || document.readyState === "complete") {
310
+ callback(...args);
311
+ } else {
312
+ document.addEventListener("DOMContentLoaded", () => callback(...args));
313
+ }
314
+ }
315
+ function toPercent(a, b) {
316
+ return b > 0 ? a / b * 100 : 0;
317
+ }
318
+ function toCamelCase(string) {
319
+ return string.split(new RegExp(/[-_.]/)).reduce(
320
+ (a, b) => a + b.charAt(0).toUpperCase() + b.slice(1)
321
+ );
322
+ }
323
+ function toSnakeCase(string) {
324
+ return toCamelCase(string).replace(/(^[A-Z])?([A-Z])/gm, "$1_$2").toLowerCase();
325
+ }
326
+ function capitalize(string) {
327
+ return string.charAt(0).toUpperCase() + string.slice(1);
328
+ }
329
+ function sortByAlphabet(first, second) {
330
+ return first.toLowerCase() > second.toLowerCase() ? 1 : -1;
331
+ }
332
+ function getRandomStr(length) {
333
+ length = length ? length > 100 ? 100 : length : 10;
334
+ let str = Math.random().toString(36).substring(2);
335
+ while (str.length < length) {
336
+ str += Math.random().toString(36).substring(2);
337
+ }
338
+ const result = str.slice(-length);
339
+ return isNaN(Number(result)) ? result : getRandomStr(length);
340
+ }
341
+ function getRandomItem(items) {
342
+ return items[Math.floor(Math.random() * items.length)];
343
+ }
344
+ function sumArray(values) {
345
+ if (values.every((value) => isNaN(value))) {
346
+ return "";
347
+ } else {
348
+ return values.reduce((sum, curr) => {
349
+ const value = Number(curr);
350
+ if (!isNaN(value)) {
351
+ return sum + value;
352
+ } else {
353
+ return sum;
354
+ }
355
+ }, 0);
356
+ }
357
+ }
358
+ function filterObjectKeysByValues(obj, values) {
359
+ values = Array.isArray(values) ? values : Array(values);
360
+ const keys = [];
361
+ for (const key in obj) {
362
+ if (!values.includes(obj[key])) {
363
+ keys.push(key);
385
364
  }
365
+ }
366
+ return keys;
386
367
  }
387
- /**
388
- * Calculate the percentage of two values
389
- *
390
- * @param a
391
- * @param b
392
- * @return number
393
- */
394
- export function toPercent(a, b) {
395
- return b > 0 ? (a / b) * 100 : 0;
396
- }
397
- /**
398
- * Make a camelCase string
399
- *
400
- * @param string
401
- * @return string
402
- */
403
- export function toCamelCase(string) {
404
- return string
405
- .split(new RegExp(/[-_.]/))
406
- .reduce((a, b) => a + b.charAt(0).toUpperCase() + b.slice(1));
407
- }
408
- /**
409
- * Make a snake_case string
410
- *
411
- * @param string
412
- * @return string
413
- */
414
- export function toSnakeCase(string) {
415
- return toCamelCase(string)
416
- .replace(/(^[A-Z])?([A-Z])/gm, "$1_$2")
417
- .toLowerCase();
418
- }
419
- /**
420
- * Transform the first letter of the given string to the upper case
421
- *
422
- * @param string
423
- * @return string
424
- */
425
- export function capitalize(string) {
426
- return string.charAt(0).toUpperCase() + string.slice(1);
427
- }
428
- /**
429
- * Registry independent string sorting
430
- *
431
- * @param first
432
- * @param second
433
- */
434
- export function sortByAlphabet(first, second) {
435
- return first.toLowerCase() > second.toLowerCase() ? 1 : -1;
436
- }
437
- /**
438
- * @param length
439
- * @return string of max length 100
440
- */
441
- export function getRandomStr(length) {
442
- length = length ? (length > 100 ? 100 : length) : 10;
443
- let str = Math.random().toString(36).substring(2);
444
- while (str.length < length) {
445
- str += Math.random().toString(36).substring(2);
446
- }
447
- const result = str.slice(-length);
448
- return isNaN(Number(result)) ? result : getRandomStr(length);
449
- }
450
- export function getRandomItem(items) {
451
- return items[Math.floor(Math.random() * items.length)];
452
- }
453
- /**
454
- * Summarize elements of the given array
455
- *
456
- * @param values
457
- * @return number | string - a summary of all the numbers in the array or an empty string if
458
- * there was only NaNs
459
- */
460
- export function sumArray(values) {
461
- if (values.every((value) => isNaN(value))) {
462
- return "";
463
- }
464
- else {
465
- return values.reduce((sum, curr) => {
466
- const value = Number(curr);
467
- if (!isNaN(value)) {
468
- return sum + value;
469
- }
470
- else {
471
- return sum;
472
- }
473
- }, 0);
474
- }
368
+ function getFromObject(object, key) {
369
+ return key.split(".").reduce((a, b) => {
370
+ return a[b];
371
+ }, object);
475
372
  }
476
- /**
477
- * Returns an array of the object keys which values are not present in filter
478
- *
479
- * @param obj
480
- * @param values
481
- */
482
- export function filterObjectKeysByValues(obj, values) {
483
- values = Array.isArray(values) ? values : Array(values);
484
- const keys = [];
485
- for (const key in obj) {
486
- if (!values.includes(obj[key])) {
487
- keys.push(key);
488
- }
373
+ function fireBlurEvent(element, delay = 0) {
374
+ fireEvent("blur", element, delay);
375
+ }
376
+ function fireInputEvent(element, delay = 0) {
377
+ fireEvent("input", element, delay);
378
+ }
379
+ function fireEvent(eventName, element, delay = 0) {
380
+ setTimeout(() => {
381
+ const target = isString(element) ? document.querySelector(element) : element;
382
+ if (target) {
383
+ target.dispatchEvent(new Event(eventName, { bubbles: true }));
489
384
  }
490
- return keys;
491
- }
492
- export function getFromObject(object, key) {
493
- return key.split(".").reduce((a, b) => {
494
- return a[b];
495
- }, object);
496
- }
497
- export function fireBlurEvent(element, delay = 0) {
498
- fireEvent("blur", element, delay);
499
- }
500
- export function fireInputEvent(element, delay = 0) {
501
- fireEvent("input", element, delay);
502
- }
503
- export function fireEvent(eventName, element, delay = 0) {
504
- setTimeout(() => {
505
- const target = isString(element)
506
- ? document.querySelector(element)
507
- : element;
508
- if (target) {
509
- target.dispatchEvent(new Event(eventName, { bubbles: true }));
510
- }
511
- }, delay);
512
- }
513
- export function hasObjectChanged(oldObj, values, checkNewKeys = false) {
514
- const newMap = new Map(values);
515
- // check keys from old
516
- for (const key of Object.keys(oldObj)) {
517
- let oldVal = oldObj[key];
518
- let newVal = newMap.get(key);
519
- if (isObject(oldVal)) {
520
- if (!isObject(newVal))
521
- return true;
522
- if (hasObjectChanged(oldVal, Object.entries(newVal), checkNewKeys))
523
- return true;
524
- continue;
525
- }
526
- if (Array.isArray(oldVal) || Array.isArray(newVal)) {
527
- const oldArr = Array.isArray(oldVal) ? oldVal : [];
528
- const newArr = Array.isArray(newVal) ? newVal : [];
529
- if (arrayDiff(newArr, oldArr).length > 0)
530
- return true;
531
- continue;
532
- }
533
- if (areDiff(newVal, oldVal))
534
- return true;
385
+ }, delay);
386
+ }
387
+ function hasObjectChanged(oldObj, values, checkNewKeys = false) {
388
+ const newMap = new Map(values);
389
+ for (const key of Object.keys(oldObj)) {
390
+ let oldVal = oldObj[key];
391
+ let newVal = newMap.get(key);
392
+ if (isObject(oldVal)) {
393
+ if (!isObject(newVal)) return true;
394
+ if (hasObjectChanged(oldVal, Object.entries(newVal), checkNewKeys))
395
+ return true;
396
+ continue;
535
397
  }
536
- // optional: check keys that exist only in new
537
- if (checkNewKeys) {
538
- for (const key of newMap.keys()) {
539
- if (!(key in oldObj))
540
- return true;
541
- }
398
+ if (Array.isArray(oldVal) || Array.isArray(newVal)) {
399
+ const oldArr = Array.isArray(oldVal) ? oldVal : [];
400
+ const newArr = Array.isArray(newVal) ? newVal : [];
401
+ if (arrayDiff(newArr, oldArr).length > 0) return true;
402
+ continue;
542
403
  }
543
- return false;
544
- }
545
- export function roundBigNum(number) {
546
- const digitsNum = Math.trunc(number).toString().length;
547
- let roundTo = 0;
548
- switch (true) {
549
- case digitsNum > 2 && digitsNum < 5:
550
- roundTo = 100;
551
- break;
552
- case digitsNum >= 5:
553
- roundTo = 10000;
554
- break;
404
+ if (areDiff(newVal, oldVal)) return true;
405
+ }
406
+ if (checkNewKeys) {
407
+ for (const key of newMap.keys()) {
408
+ if (!(key in oldObj)) return true;
555
409
  }
556
- return roundTo ? Math.round(number / roundTo) * roundTo : number;
557
- }
558
- export function extractNumbers(value) {
559
- if (!isString(value) && !isNum(value)) {
560
- return "";
410
+ }
411
+ return false;
412
+ }
413
+ function roundBigNum(number) {
414
+ const digitsNum = Math.trunc(number).toString().length;
415
+ let roundTo = 0;
416
+ switch (true) {
417
+ case (digitsNum > 2 && digitsNum < 5):
418
+ roundTo = 100;
419
+ break;
420
+ case digitsNum >= 5:
421
+ roundTo = 1e4;
422
+ break;
423
+ }
424
+ return roundTo ? Math.round(number / roundTo) * roundTo : number;
425
+ }
426
+ function extractNumbers(value) {
427
+ if (!isString(value) && !isNum(value)) {
428
+ return "";
429
+ }
430
+ return value.toString().replace(/[^0-9]/g, "");
431
+ }
432
+ function removeSpaces(value) {
433
+ if (!isString(value) && !isNum(value)) {
434
+ return "";
435
+ }
436
+ return value.toString().replace(/\s/g, "");
437
+ }
438
+ function roundUp(num, precision) {
439
+ const multiplier = Number("1".padEnd(precision + 1, "0"));
440
+ return Math.ceil(num * multiplier) / multiplier;
441
+ }
442
+ function roundDown(num, precision) {
443
+ const multiplier = Number("1".padEnd(precision + 1, "0"));
444
+ return Math.floor(num * multiplier) / multiplier;
445
+ }
446
+ function areDiff(val1, val2, strict) {
447
+ if (strict) {
448
+ return val1 !== val2;
449
+ }
450
+ if (Boolean(val1) || Boolean(val2)) {
451
+ return val1 != val2;
452
+ }
453
+ return false;
454
+ }
455
+ function flattenObject(obj, prefix = "") {
456
+ const pre = prefix ? `${prefix}.` : "";
457
+ return Object.keys(obj).reduce((acc, k) => {
458
+ const val = obj[k];
459
+ const key = `${pre}${k}`;
460
+ if ((isObject(val) || Array.isArray(val)) && getObjectKeys(obj[k]).length > 0) {
461
+ Object.assign(acc, flattenObject(val, key));
462
+ } else {
463
+ acc[key] = val;
561
464
  }
562
- return value.toString().replace(/[^0-9]/g, "");
563
- }
564
- export function removeSpaces(value) {
565
- if (!isString(value) && !isNum(value)) {
566
- return "";
465
+ return acc;
466
+ }, {});
467
+ }
468
+ function flattenObjectAsArray(obj) {
469
+ const flat = flattenObject(obj);
470
+ const result = {};
471
+ for (const key of Object.keys(flat)) {
472
+ const newKey = key.replace(/\.([^.]+)/g, "[$1]");
473
+ result[newKey] = flat[key];
474
+ }
475
+ return result;
476
+ }
477
+ function parseObjectPathStr(pathStr) {
478
+ const pathParts = pathStr.replace(/\[/g, ".").replace(/\]/g, "").split(".");
479
+ const [first, second] = pathParts;
480
+ if (isString(first) && isString(second) && second.includes("[")) {
481
+ return [first, ...parseObjectPathStr(second)];
482
+ }
483
+ return pathParts;
484
+ }
485
+ function formatNumber(num, fractionDigits) {
486
+ fractionDigits = isNullOrUndef(fractionDigits) ? 2 : fractionDigits;
487
+ return new Intl.NumberFormat("ru-RU", {
488
+ style: "decimal",
489
+ minimumFractionDigits: fractionDigits,
490
+ maximumFractionDigits: fractionDigits
491
+ }).format(Number(num)).replace(",", ".").replace(/\u00A0/g, " ");
492
+ }
493
+ function formatNumberWithSign(num, fractionDigits) {
494
+ return formatWithSign(num, formatNumber(num, fractionDigits));
495
+ }
496
+ function formatPercent(num) {
497
+ return formatNumber(num) + "%";
498
+ }
499
+ function formatWithSign(num, numString) {
500
+ numString = numString ? numString : num.toString();
501
+ return (Number(num) < 0 ? "" : "+") + numString;
502
+ }
503
+ function autoSizeText(el, height, minFontSize, maxFontSize = 50) {
504
+ let attempts = 30;
505
+ const resizeText = () => {
506
+ if (getTextHeight() === 0) {
507
+ return;
567
508
  }
568
- return value.toString().replace(/\s/g, "");
569
- }
570
- export function roundUp(num, precision) {
571
- const multiplier = Number("1".padEnd(precision + 1, "0"));
572
- return Math.ceil(num * multiplier) / multiplier;
573
- }
574
- export function roundDown(num, precision) {
575
- const multiplier = Number("1".padEnd(precision + 1, "0"));
576
- return Math.floor(num * multiplier) / multiplier;
577
- }
578
- export function areDiff(val1, val2, strict) {
579
- if (strict) {
580
- return val1 !== val2;
509
+ while (attempts && getTextHeight() > height) {
510
+ attempts--;
511
+ reduceText();
581
512
  }
582
- // at least one value is not empty
583
- if (Boolean(val1) || Boolean(val2)) {
584
- return val1 != val2;
513
+ while (attempts && getTextHeight() < height) {
514
+ attempts--;
515
+ enlargeText();
585
516
  }
586
- // both empty, but not equally empty!
587
- // each one may be one of: empty string, null or undefined
588
- return false;
589
- }
590
- export function flattenObject(obj, prefix = "") {
591
- const pre = prefix ? `${prefix}.` : "";
592
- return Object.keys(obj).reduce((acc, k) => {
593
- const val = obj[k];
594
- const key = `${pre}${k}`;
595
- if (isObject(val) || Array.isArray(val)) {
596
- Object.assign(acc, flattenObject(val, key));
597
- }
598
- else {
599
- acc[key] = val;
600
- }
601
- return acc;
602
- }, {});
603
- }
604
- export function flattenObjectAsArray(obj) {
605
- const flat = flattenObject(obj);
606
- const result = {};
607
- for (const key of Object.keys(flat)) {
608
- const newKey = key.replace(/\.([^.]+)/g, "[$1]");
609
- result[newKey] = flat[key];
517
+ };
518
+ const reduceText = () => {
519
+ const fontSize = getNumericStyleProp("fontSize", el);
520
+ const newFontSize = fontSize - 1;
521
+ if (fontSize > 1 && newFontSize >= minFontSize) {
522
+ el.style.fontSize = `${newFontSize}px`;
610
523
  }
611
- return result;
612
- }
613
- export function parseObjectPathStr(pathStr) {
614
- const pathParts = pathStr.replace(/\[/g, ".").replace(/\]/g, "").split(".");
615
- if (pathParts[0] && pathParts[1] && pathParts[1].includes("[")) {
616
- return [pathParts[0], ...parseObjectPathStr(pathParts[1])];
524
+ };
525
+ const enlargeText = () => {
526
+ const fontSize = getNumericStyleProp("fontSize", el);
527
+ const newFontSize = fontSize + 1;
528
+ if (newFontSize <= maxFontSize) {
529
+ el.style.fontSize = `${newFontSize}px`;
617
530
  }
618
- return pathParts;
619
- }
620
- export function formatNumber(num, fractionDigits) {
621
- fractionDigits = isNullOrUndef(fractionDigits) ? 2 : fractionDigits;
622
- return new Intl.NumberFormat("ru-RU", {
623
- style: "decimal",
624
- minimumFractionDigits: fractionDigits,
625
- maximumFractionDigits: fractionDigits,
626
- })
627
- .format(Number(num))
628
- .replace(",", ".")
629
- .replace(/\u00A0/g, " "); // charCode 160, White-space
630
- }
631
- export function formatNumberWithSign(num, fractionDigits) {
632
- return formatWithSign(num, formatNumber(num, fractionDigits));
633
- }
634
- export function formatPercent(num) {
635
- return formatNumber(num) + "%";
636
- }
637
- export function formatWithSign(num, numString) {
638
- numString = numString ? numString : num.toString();
639
- return (Number(num) < 0 ? "" : "+") + numString;
640
- }
641
- export function autoSizeText(el, height, minFontSize, maxFontSize = 50) {
642
- let attempts = 30;
643
- const resizeText = () => {
644
- if (getTextHeight() === 0) {
645
- return;
646
- }
647
- while (attempts && getTextHeight() > height) {
648
- attempts--;
649
- reduceText();
650
- }
651
- while (attempts && getTextHeight() < height) {
652
- attempts--;
653
- enlargeText();
654
- }
655
- };
656
- const reduceText = () => {
657
- const fontSize = getNumericStyleProp("fontSize", el);
658
- const newFontSize = fontSize - 1;
659
- if (fontSize > 1 && newFontSize >= minFontSize) {
660
- el.style.fontSize = `${newFontSize}px`;
661
- }
662
- };
663
- const enlargeText = () => {
664
- const fontSize = getNumericStyleProp("fontSize", el);
665
- const newFontSize = fontSize + 1;
666
- if (newFontSize <= maxFontSize) {
667
- el.style.fontSize = `${newFontSize}px`;
668
- }
669
- };
670
- const getTextHeight = () => Math.floor(el.scrollHeight -
671
- getNumericStyleProp("paddingTop", el) -
672
- getNumericStyleProp("paddingBottom", el));
673
- resizeText();
674
- }
675
- //# sourceMappingURL=index.js.map
531
+ };
532
+ const getTextHeight = () => Math.floor(
533
+ el.scrollHeight - getNumericStyleProp("paddingTop", el) - getNumericStyleProp("paddingBottom", el)
534
+ );
535
+ resizeText();
536
+ }
537
+ async function monitor(fn, interval = 10, attempts = 100) {
538
+ for (let i = 0; i < attempts; i++) {
539
+ if (await fn()) return true;
540
+ if (i < attempts - 1) {
541
+ await new Promise((r) => setTimeout(r, interval));
542
+ }
543
+ }
544
+ return false;
545
+ }
546
+
547
+ exports.areDiff = areDiff;
548
+ exports.arrayDiff = arrayDiff;
549
+ exports.arrayIntersect = arrayIntersect;
550
+ exports.autoSizeText = autoSizeText;
551
+ exports.capitalize = capitalize;
552
+ exports.countObjectInnerLength = countObjectInnerLength;
553
+ exports.createHtmlElement = createHtmlElement;
554
+ exports.createLinkElement = createLinkElement;
555
+ exports.createPixelElement = createPixelElement;
556
+ exports.createScriptElement = createScriptElement;
557
+ exports.createStyleElement = createStyleElement;
558
+ exports.createSvgElement = createSvgElement;
559
+ exports.debounce = debounce;
560
+ exports.decodeSafeURL = decodeSafeURL;
561
+ exports.deepCloneObject = deepCloneObject;
562
+ exports.encodeQueryString = encodeQueryString;
563
+ exports.extractNumbers = extractNumbers;
564
+ exports.filterObjectKeysByValues = filterObjectKeysByValues;
565
+ exports.fireBlurEvent = fireBlurEvent;
566
+ exports.fireEvent = fireEvent;
567
+ exports.fireInputEvent = fireInputEvent;
568
+ exports.flatHtmlAttributes = flatHtmlAttributes;
569
+ exports.flattenObject = flattenObject;
570
+ exports.flattenObjectAsArray = flattenObjectAsArray;
571
+ exports.formatNumber = formatNumber;
572
+ exports.formatNumberWithSign = formatNumberWithSign;
573
+ exports.formatPercent = formatPercent;
574
+ exports.formatWithSign = formatWithSign;
575
+ exports.getFromObject = getFromObject;
576
+ exports.getHtmlElement = getHtmlElement;
577
+ exports.getNumericStyleProp = getNumericStyleProp;
578
+ exports.getObjectKeys = getObjectKeys;
579
+ exports.getRandomInt = getRandomInt;
580
+ exports.getRandomItem = getRandomItem;
581
+ exports.getRandomStr = getRandomStr;
582
+ exports.getSafeURL = getSafeURL;
583
+ exports.getScreenSize = getScreenSize;
584
+ exports.hasObjectChanged = hasObjectChanged;
585
+ exports.hashCode = hashCode;
586
+ exports.injectScript = injectScript;
587
+ exports.injectStyleLink = injectStyleLink;
588
+ exports.insertCss = insertCss;
589
+ exports.insertHtmlElements = insertHtmlElements;
590
+ exports.insertJs = insertJs;
591
+ exports.isBool = isBool;
592
+ exports.isDefined = isDefined;
593
+ exports.isElementVisible = isElementVisible;
594
+ exports.isFn = isFn;
595
+ exports.isHTMLElement = isHTMLElement;
596
+ exports.isNotEmptyString = isNotEmptyString;
597
+ exports.isNullOrUndef = isNullOrUndef;
598
+ exports.isNum = isNum;
599
+ exports.isObject = isObject;
600
+ exports.isStr = isStr;
601
+ exports.isString = isString;
602
+ exports.isUndef = isUndef;
603
+ exports.monitor = monitor;
604
+ exports.objectHasProp = objectHasProp;
605
+ exports.objectToQueryString = objectToQueryString;
606
+ exports.onDOMReady = onDOMReady;
607
+ exports.parseObjectPathStr = parseObjectPathStr;
608
+ exports.parseURL = parseURL;
609
+ exports.removeSpaces = removeSpaces;
610
+ exports.roundBigNum = roundBigNum;
611
+ exports.roundDown = roundDown;
612
+ exports.roundUp = roundUp;
613
+ exports.sortByAlphabet = sortByAlphabet;
614
+ exports.stringToHtmlElements = stringToHtmlElements;
615
+ exports.sumArray = sumArray;
616
+ exports.throttle = throttle;
617
+ exports.toBinaryStr = toBinaryStr;
618
+ exports.toCamelCase = toCamelCase;
619
+ exports.toPercent = toPercent;
620
+ exports.toSnakeCase = toSnakeCase;
621
+ //# sourceMappingURL=index.js.map