@minsize/utils 0.0.15 → 0.0.17

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
@@ -7,27 +7,35 @@ npm i @minsize/utils
7
7
  yarn add @minsize/utils
8
8
  ```
9
9
 
10
- | Function | Description |
11
- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
12
- | `chunks` | Splits an array into pieces of the given size. |
13
- | `clamp` | Limits the number to the specified minimum and maximum value. |
14
- | `decWord` | The function returns a string representing the correct ending of the word depending on the number. |
15
- | `alignTo` | The function returns an aligned number. |
16
- | `toShort` | The function returns a string representing the number in short form. |
17
- | `timeAgo` | The function returns a string describing the time elapsed since timestamp. |
18
- | `formatNumber` | Formats a number into a delimited string. |
19
- | `shuffle` | Shuffles the elements of an array in random order. |
20
- | `random` | Generates a random number within the specified range. |
21
- | `isType` | Checks if the value is of the specified type. |
22
- | `omit` | Returns a new object with no specified keys. |
23
- | `pick` | Returns a new object with the selected keys. |
24
- | `sleep` | Waits for the specified number of milliseconds. |
25
- | `copyText` | The function allows you to copy text to the clipboard. |
26
- | `createLinksFromText` | The function returns an array containing text fragments and the results of the callback call for each block. |
27
- | `HSVtoRGB` | The function converts color from HSV color model (hue, saturation, brightness) to RGB color model (red, green, blue). |
28
- | `RGBtoHEX` | The function converts color from the RGB color model (red, green, blue) to hexadecimal format (HEX). |
29
- | `RGBtoHSV` | The function converts color from the RGB (red, green, blue) color model to the HSV (hue, saturation, brightness) color model. |
30
- | `HEXtoRGB` | The function converts color from hexadecimal format (HEX) to the RGB color model (red, green, blue). |
31
- | `comparison` | Compares two objects for deep equality, including arrays (order-sensitive). |
32
- | `generateUniqueKey` | Generates a unique key for an arbitrary JavaScript object using hashing |
33
-
10
+ | Функция | Описание |
11
+ | --------------------- | --------------------------------------------------------------------------------------------- |
12
+ | `chunks` | Разбивает массив на части заданного размера. |
13
+ | `clamp` | Ограничивает число указанным минимальным и максимальным значением. |
14
+ | `decWord` | Возвращает строку с правильным окончанием слова в зависимости от числа. |
15
+ | `alignTo` | Возвращает выровненное число. |
16
+ | `toShort` | Возвращает строку, представляющую число в сокращенной форме. |
17
+ | `timeAgo` | Возвращает строку, описывающую время, прошедшее с момента отметки времени. |
18
+ | `formatNumber` | Форматирует число в виде строки с разделителями. |
19
+ | `shuffle` | Перемешивает элементы массива в случайном порядке. |
20
+ | `random` | Генерирует случайное число в указанном диапазоне. |
21
+ | `randomByWeight` | Выбирает случайный элемент на основе весов из набора элементов с весами. |
22
+ | `isType` | Проверяет, является ли значение указанного типа. |
23
+ | `omit` | Возвращает новый объект без указанных ключей. |
24
+ | `pick` | Возвращает новый объект с выбранными ключами. |
25
+ | `sleep` | Ожидает указанное количество миллисекунд. |
26
+ | `copyText` | Позволяет копировать текст в буфер обмена. |
27
+ | `createLinksFromText` | Возвращает массив, содержащий фрагменты текста и результаты вызова колбэка для каждого блока. |
28
+ | `HSVtoRGB` | Преобразует цвет из модели HSV в модель RGB. |
29
+ | `RGBtoHEX` | Преобразует цвет из модели RGB в шестнадцатеричный формат (HEX). |
30
+ | `RGBtoHSV` | Преобразует цвет из модели RGB в модель HSV. |
31
+ | `HEXtoRGB` | Преобразует цвет из шестнадцатеричного формата (HEX) в модель RGB. |
32
+ | `comparison` | Сравнивает два объекта на глубокое равенство, включая массивы учетом порядка). |
33
+ | `generateUniqueKey` | Генерирует уникальный ключ для произвольного JavaScript объекта с использованием хэширования. |
34
+ | `unlink` | Удаляет связь или ссылку между элементами или объектами. |
35
+ | `textParserUrl` | Разбирает текст для извлечения и обработки URL. |
36
+ | `memoize` | Запоминает результаты вызова функции, чтобы оптимизировать её производительность. |
37
+ | `retry` | Повторяет выполнение функции при неудаче, например, при временных сбоях. |
38
+ | `unique` | Возвращает массив, содержащий только уникальные элементы исходного массива. |
39
+ | `parseQueryString` | Преобразует строку запроса URL в объект с параметрами и их значениями. |
40
+ | `groupBy` | Группирует элементы массива по заданному критерию. |
41
+ | `orderBy` | Сортирует массив объектов по указанным вложенным ключам и направлениям. |
package/index.d.ts CHANGED
@@ -38,9 +38,18 @@ declare const formatNumber: (number: number) => string;
38
38
  * shuffle([1,2,3]) // return: [2,1,3]
39
39
  * shuffle([1,2,3]) // return: [3,1,2]
40
40
  */
41
- declare const shuffle: <T>(array: T[]) => T[];
41
+ declare const shuffle: <T>(array: T[], seed?: number) => T[];
42
42
 
43
- declare const random: (min: number, max: number) => number;
43
+ declare function random(min: number, max: number, seed?: number): number;
44
+
45
+ /**
46
+ * Функция для выбора случайного элемента из объекта items на основе весов, с возможностью использования seed для случайности.
47
+ * @template Items
48
+ * @param {Items} items - Объект, представляющий элементы и их веса.
49
+ * @param {number} [seed] - Необязательное значение для начального состояния генерации случайных чисел.
50
+ * @returns {string} Выбор случайного элемента на основе указанных весов.
51
+ */
52
+ declare function randomByWeight<Items extends Record<string, number>>(items: Items, seed?: number): Extract<keyof Items, string>;
44
53
 
45
54
  type Type = "string" | "number" | "bigint" | "nan" | "boolean" | "object" | "array" | "function" | "null" | "undefined" | "symbol" | "date" | "regexp" | "error" | "unknown" | "map" | "set" | "weakmap" | "weakset" | "promise" | "buffer";
46
55
  /**
@@ -129,6 +138,58 @@ interface TextToken {
129
138
  }
130
139
  declare const textParserUrl: (input: string, options?: TextParserOptions) => TextToken[];
131
140
 
141
+ /**
142
+ * Функция мемоизации, которая сохраняет результаты вызовов функции `fn` с определенными аргументами.
143
+ * @template F - Параметр типа для функции, которая принимается на вход.
144
+ * @param {F} fn - Функция, результат выполнения которой необходимо запоминать.
145
+ * @returns {F} - Меморизованная версия переданной функции.
146
+ */
147
+ declare function memoize<F extends (...args: any[]) => any>(fn: F): F;
148
+
149
+ /**
150
+ * Повторяет выполнение асинхронной функции до тех пор, пока она не завершится успешно или не будет достигнуто максимальное количество попыток.
151
+ * @template T - Тип результата, который возвращает функция.
152
+ * @param {() => Promise<T>} fn - Асинхронная функция, которую нужно выполнять повторно.
153
+ * @param {number} retries - Максимальное количество попыток.
154
+ * @param {number} delay - Интервал между попытками в миллисекундах.
155
+ * @returns {Promise<T>} - Возвращает Promise с результатом выполнения функции или ошибкой после всех попыток.
156
+ */
157
+ declare function retry<T>(fn: () => Promise<T>, retries: number, delay: number): Promise<T>;
158
+
159
+ /**
160
+ * Возвращает новый массив, содержащий только уникальные элементы из исходного массива.
161
+ * @param {T[]} array - Исходный массив.
162
+ * @returns {T[]} - Массив уникальных элементов.
163
+ */
164
+ declare function unique<T>(array: T[]): T[];
165
+
166
+ /**
167
+ * Разбирает строку запроса URL и возвращает объект с параметрами запроса.
168
+ * @param {string} queryString - Строка запроса, начинающаяся с '?'.
169
+ * @returns {Record<string, string>} - Объект, представляющий параметры запроса и их значения.
170
+ */
171
+ declare function parseQueryString<Result extends Record<string, string>>(queryString: string): Result;
172
+
173
+ /**
174
+ * Группирует элементы массива по заданному критерию.
175
+ * @param {T[]} array - Массив элементов, которые нужно сгруппировать.
176
+ * @param {(item: T) => K} keyGetter - Функция, определяющая ключ группы для каждого элемента.
177
+ * @returns {Record<string, T[]>} - Объект, где ключами являются результаты keyGetter, а значениями — массивы элементов.
178
+ */
179
+ declare function groupBy<T, K extends string | number>(array: T[], keyGetter: (item: T) => K): Record<K, T[]>;
180
+
181
+ type SortDirection = "asc" | "desc";
182
+ type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? Key | `${Key}.${PathImpl<T[Key], keyof T[Key]>}` : Key : never;
183
+ type Path<T> = PathImpl<T, keyof T>;
184
+ /**
185
+ * Сортирует массив объектов по указанным вложенным ключам и направлениям.
186
+ * @param array - Массив объектов для сортировки.
187
+ * @param criteria - Объект, где ключи — путь к полям для сортировки (точечная нотация),
188
+ * а значения — направления ('asc' или 'desc').
189
+ * @returns Отсортированный массив.
190
+ */
191
+ declare function orderBy<T>(array: T[], criteria: Partial<Record<Path<T>, SortDirection>>): T[];
192
+
132
193
  /**
133
194
  * @returns [r,g,b]
134
195
  */
@@ -143,4 +204,4 @@ declare const RGBtoHSV: (r: number, g: number, b: number) => [number, number, nu
143
204
 
144
205
  declare const HEXtoRGB: (hex: string) => [number, number, number];
145
206
 
146
- export { HEXtoRGB, HSVtoRGB, RGBtoHEX, RGBtoHSV, alignTo, chunks, clamp, comparison, copyText, createLinksFromText, decWord, formatNumber, generateUniqueKey, isType, omit, pick, random, shuffle, sleep, textParserUrl, timeAgo, toShort, unlink };
207
+ export { HEXtoRGB, HSVtoRGB, RGBtoHEX, RGBtoHSV, alignTo, chunks, clamp, comparison, copyText, createLinksFromText, decWord, formatNumber, generateUniqueKey, groupBy, isType, memoize, omit, orderBy, parseQueryString, pick, random, randomByWeight, retry, shuffle, sleep, textParserUrl, timeAgo, toShort, unique, unlink };
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";const e=(e,t)=>t[e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2];const t={date:e=>e instanceof Date,regexp:e=>e instanceof RegExp,error:e=>e instanceof Error,map:e=>e instanceof Map,set:e=>e instanceof Set,weakmap:e=>e instanceof WeakMap,weakset:e=>e instanceof WeakSet,promise:e=>e instanceof Promise,buffer:e=>e instanceof Buffer,undefined:e=>void 0===e,string:e=>"string"==typeof e,bigint:e=>"bigint"==typeof e,number:e=>"number"==typeof e&&!isNaN(e),nan:e=>"number"==typeof e&&isNaN(e),boolean:e=>"boolean"==typeof e,array:e=>Array.isArray(e),object:e=>"object"==typeof e&&!Array.isArray(e)&&null!==e,function:e=>"function"==typeof e,null:e=>null===e,symbol:e=>"symbol"==typeof e,unknown:()=>!0};const r=(e,t)=>{if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return e===t;if("[object Map]"===Object.prototype.toString.call(e)&&"[object Map]"===Object.prototype.toString.call(t))return n(e,t);const o=Object.keys(e);if(o.length!==Object.keys(t).length)return!1;for(let n of o){if(!t.hasOwnProperty(n))return!1;const o=e[n],a=t[n];if(Array.isArray(o)&&Array.isArray(a)){if(o.length!==a.length)return!1;for(let e=0;e<o.length;e++)if(!r(o[e],a[e]))return!1}else if(!r(o,a))return!1}return!0},n=(e,t)=>{if(e.size!==t.size)return!1;for(const[n,o]of e){if(!t.has(n))return!1;if(!r(t.get(n),o))return!1}return!0},o=e=>Object.prototype.toString.call(e),a=(e,t)=>{switch(t||o(t)){case"[object Number]":return Number(String(e));case"[object String]":return String(e);case"[object BigInt]":return BigInt(String(e));case"[object Map]":return new Map(e);case"[object Set]":return new Set(e);default:return e}},s=e=>{const t=[];for(const r of e){const e=o(r);"[object Array]"===e?t.push(s(r)):"[object Object]"===e?t.push(c(r)):t.push(a(r))}return t},c=e=>{const t={},r=Object.keys(e);for(const n of r){const r=o(e[n]);t[n]="[object Array]"===r?s(e[n]):"[object Object]"===r?c(e[n]):e[n]}return t},i=new RegExp(/(?:https?:\/\/)?(?:www\.)?([А-Яа-яa-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.(?:ru|com|org|net|me|su|рф|biz|info|co|uk|de|fr|jp|cn|es|it|ca|au|nl|se|no|dk|fi|pl|at|ch|be|cz|ie|pt|ro|hu|gr|sk|bg|hr|si|lt|lv|ee|is|mt|lu|li|mc|sm|va|ad|al|ba|mk|me|rs|tr|ua|by|kz|uz|am|ge|az|tm|kg|tj|md|kg|tj|af|dz|bh|eg|iq|ir|jo|kw|lb|ly|ma|om|ps|qa|sa|sd|sy|tn|ae|ye|ar|bo|br|cl|co|ec|gf|gy|pe|py|sr|uy|ve|ag|ai|aw|bb|bm|bs|bz|ca|cr|cu|dm|do|gd|gp|gt|hn|ht|jm|kn|ky|lc|ms|mx|ni|pa|pr|sv|tc|tt|vc|vg|vi|an|aq|as|fj|fm|gu|hm|id|ki|mh|mp|nc|nf|nr|nu|pf|pg|pw|sb|tk|to|tv|vu|wf|ws)(?:\/[a-zA-Z0-9._~:\/?#[\]@!$&'()*+,;=-]*)?)(?:\s)/),u=new RegExp(/(?:https?:\/\/)(?:www\.)?([А-Яа-яa-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.(?:ru|com|org|net|me|su|рф|biz|info|co|uk|de|fr|jp|cn|es|it|ca|au|nl|se|no|dk|fi|pl|at|ch|be|cz|ie|pt|ro|hu|gr|sk|bg|hr|si|lt|lv|ee|is|mt|lu|li|mc|sm|va|ad|al|ba|mk|me|rs|tr|ua|by|kz|uz|am|ge|az|tm|kg|tj|md|kg|tj|af|dz|bh|eg|iq|ir|jo|kw|lb|ly|ma|om|ps|qa|sa|sd|sy|tn|ae|ye|ar|bo|br|cl|co|ec|gf|gy|pe|py|sr|uy|ve|ag|ai|aw|bb|bm|bs|bz|ca|cr|cu|dm|do|gd|gp|gt|hn|ht|jm|kn|ky|lc|ms|mx|ni|pa|pr|sv|tc|tt|vc|vg|vi|an|aq|as|fj|fm|gu|hm|id|ki|mh|mp|nc|nf|nr|nu|pf|pg|pw|sb|tk|to|tv|vu|wf|ws)(?:\/[a-zA-Z0-9._~:\/?#[\]@!$&'()*+,;=-]*)?)(?:\s)/),l=e=>e,p=e=>{const t=e.toString(16);return 1==t.length?"0"+t:t};exports.HEXtoRGB=e=>{if(3===(e=e.replace("#","")).length&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),6!==e.length)return[0,0,0];const t=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),n=parseInt(e.substring(4,6),16);return isNaN(t)||isNaN(r)||isNaN(n)||t<0||t>255||r<0||r>255||n<0||n>255?[0,0,0]:[t,r,n]},exports.HSVtoRGB=(e,t,r)=>{var n,o,a,s,c,i,u,l;switch(i=r*(1-t),u=r*(1-(c=6*e-(s=Math.floor(6*e)))*t),l=r*(1-(1-c)*t),s%6){case 0:n=r,o=l,a=i;break;case 1:n=u,o=r,a=i;break;case 2:n=i,o=r,a=l;break;case 3:n=i,o=u,a=r;break;case 4:n=l,o=i,a=r;break;case 5:n=r,o=i,a=u}return[Math.round(255*n),Math.round(255*o),Math.round(255*a)]},exports.RGBtoHEX=(e,t,r)=>"#"+p(e)+p(t)+p(r),exports.RGBtoHSV=(e,t,r)=>{var n=Math.max(e,t,r),o=Math.min(e,t,r),a=n-o,s=0,c=0===n?0:a/n,i=n/255;switch(n){case o:s=0;break;case e:s=t-r+a*(t<r?6:0),s/=6*a;break;case t:s=r-e+2*a,s/=6*a;break;case r:s=e-t+4*a,s/=6*a}return[s,c,i]},exports.alignTo=function(e,t){return e<=0?t:e+(t-e%t)%t},exports.chunks=(e,t)=>{const r=[];for(let n=0;n<t.length;n+=e)r.push(t.slice(n,n+e));return r},exports.clamp=(e,t,r)=>e>t?e<r?e:r:t,exports.comparison=r,exports.copyText=e=>{if(!e)return!1;try{return navigator.clipboard?.writeText(e),!0}catch{}try{var t=document.createElement("input");return t.value=e,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),!0}catch{}return!1},exports.createLinksFromText=(e,t)=>{const r=[],n=/{{([^}]+):([^}]+)}}/g;let o,a=0;for(;null!==(o=n.exec(e));)r.push(e.substring(a,o.index)),a=o.index+o[0].length,r.push({key:o[1],text:o[2]});return r.push(e.substring(a)),r.map((e=>"string"==typeof e?e:t(e.key,e.text)))},exports.decWord=e,exports.formatNumber=e=>(e||0).toString().replace(/\B(?=(\d{3})+(?!\d))/g,"."),exports.generateUniqueKey=e=>{const t=e=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e||null===e)return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(t).join(",")+"]";if("object"==typeof e){const r=Object.keys(e).sort();let n="{";for(let o=0;o<r.length;o++){const a=r[o];n+=JSON.stringify(a)+":"+t(e[a]),o<r.length-1&&(n+=",")}return n+="}",n}return String(e)},r=e=>{let t=0;if(0===e.length)return t;for(let r=0;r<e.length;r++){t=(t<<5)-t+e.charCodeAt(r),t|=0}return t};try{const n=t(e);return r(n).toString(16)}catch(t){return console.warn(`Object could not be fully stringified. Using a simple string conversion. Error: ${t}`),r(String(e)).toString(16)}},exports.isType=function(e,r){for(const[n,o]of Object.entries(t))if(o(e))return void 0!==r?n===r:n;return void 0===r&&"unknown"},exports.omit=function(e,t){return Object.keys(e).reduce(((r,n)=>(t.includes(n)||(r[n]=e[n]),r)),{})},exports.pick=function(e,t){return Object.keys(e).reduce(((r,n)=>(t.includes(n)&&(r[n]=e[n]),r)),{})},exports.random=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),exports.shuffle=e=>{for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}return e},exports.sleep=async e=>await new Promise((t=>setTimeout(t,e))),exports.textParserUrl=(e,t)=>{const r=t?.onToken??l,n=t?.requireProtocol??!1,o=t?.regex??n?u:i,a=[];let s=e+" ",c=o.exec(s);for(;c;){const e=c[0].trim(),t=c.index;t>0&&(a.push(r({type:"raw",value:s.substring(0,t)})),s=s.substring(t)),a.push(r({type:"url",value:e})),s=s.substring(e.length),c=o.exec(s)}return s.length>0&&a.push(r({type:"raw",value:s})),a},exports.timeAgo=t=>{if(!t)return"только что";const r=new Date(t),n=Math.floor((Date.now()-r.getTime())/1e3),o=()=>new Intl.DateTimeFormat("RU-ru",{day:"numeric",month:"short"}).format(r).replace(".",""),a=()=>r.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),s=(t,r,n)=>Array.isArray(t)?`${n} ${e(n,t)} ${r}`:`${t} ${r}`;switch(!0){case n<0:return"скоро";case n<60:return s(["секунду","секунды","секунд"],"назад",n);case n<3600:return s(["минуту","минуты","минут"],"назад",Math.floor(n/60));case n<7200:return s("час","назад",Math.floor(n/3600));case n<10800:return s("два часа","назад",Math.floor(n/3600));case n<14400:return s("три часа","назад",Math.floor(n/3600));case n<86400:return s(`сегодня в ${a()}`,"",Math.floor(n/3600));case n<172800:return s(`вчера в ${a()}`,"",Math.floor(n/86400));case n<259200:return s("два дня","назад",Math.floor(n/86400));case n<345600:return s("три дня","назад",Math.floor(n/86400));case n<31536e3:return s(`${o()} в ${a()}`,"",Math.floor(n/86400));case n>=31536e3:return s(`${o()} ${r.getFullYear()} г.`,"",Math.floor(n/31536e3))}return"только что"},exports.toShort=(e,t,r=1)=>{const n=t||["","k","M","G","T","P"],o=e<0,a=Math.abs(e),s=Math.log10(a)/3|0,c=a/10**(3*s);return parseFloat(`${o?"-":""}${c%1?(Math.floor(10*c)/10).toFixed(r):c}`)+n[s]},exports.unlink=e=>{switch(o(e)){case"[object Array]":return s(e);case"[object Object]":return c(e);default:return a(e)}};
1
+ "use strict";const t=(t,e)=>e[t%10==1&&t%100!=11?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2];function e(t,e,r){if(!r){const t=new Date;r=t.getDate()*t.getFullYear()*(t.getHours()??1)*t.getMilliseconds()}const n=function(t){const e=2**32;let r=t;return function(){var t;return r=(1664525*r+1013904223)%e,t=r,t^=t>>>21,r=(t^=t<<35)^t>>>4,(r>>>0)/e}}(r);return function(t,e,r){if(e>r)throw new Error("Минимальная граница не может быть больше максимальной.");return Math.floor(t()*(r-e+1))+e}(n,t,e)}const r={date:t=>t instanceof Date,regexp:t=>t instanceof RegExp,error:t=>t instanceof Error,map:t=>t instanceof Map,set:t=>t instanceof Set,weakmap:t=>t instanceof WeakMap,weakset:t=>t instanceof WeakSet,promise:t=>t instanceof Promise,buffer:t=>t instanceof Buffer,undefined:t=>void 0===t,string:t=>"string"==typeof t,bigint:t=>"bigint"==typeof t,number:t=>"number"==typeof t&&!isNaN(t),nan:t=>"number"==typeof t&&isNaN(t),boolean:t=>"boolean"==typeof t,array:t=>Array.isArray(t),object:t=>"object"==typeof t&&!Array.isArray(t)&&null!==t,function:t=>"function"==typeof t,null:t=>null===t,symbol:t=>"symbol"==typeof t,unknown:()=>!0};const n=(t,e)=>{if(t===e)return!0;if("object"!=typeof t||null===t||"object"!=typeof e||null===e)return t===e;if("[object Map]"===Object.prototype.toString.call(t)&&"[object Map]"===Object.prototype.toString.call(e))return o(t,e);const r=Object.keys(t);if(r.length!==Object.keys(e).length)return!1;for(let o of r){if(!e.hasOwnProperty(o))return!1;const r=t[o],s=e[o];if(Array.isArray(r)&&Array.isArray(s)){if(r.length!==s.length)return!1;for(let t=0;t<r.length;t++)if(!n(r[t],s[t]))return!1}else if(!n(r,s))return!1}return!0},o=(t,e)=>{if(t.size!==e.size)return!1;for(const[r,o]of t){if(!e.has(r))return!1;if(!n(e.get(r),o))return!1}return!0},s=t=>Object.prototype.toString.call(t),c=(t,e)=>{switch(e||s(e)){case"[object Number]":return Number(String(t));case"[object String]":return String(t);case"[object BigInt]":return BigInt(String(t));case"[object Map]":return new Map(t);case"[object Set]":return new Set(t);default:return t}},a=t=>{const e=[];for(const r of t){const t=s(r);"[object Array]"===t?e.push(a(r)):"[object Object]"===t?e.push(i(r)):e.push(c(r))}return e},i=t=>{const e={},r=Object.keys(t);for(const n of r){const r=s(t[n]);e[n]="[object Array]"===r?a(t[n]):"[object Object]"===r?i(t[n]):t[n]}return e},u=new RegExp(/(?:https?:\/\/)?(?:www\.)?([А-Яа-яa-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.(?:ru|com|org|net|me|su|рф|biz|info|co|uk|de|fr|jp|cn|es|it|ca|au|nl|se|no|dk|fi|pl|at|ch|be|cz|ie|pt|ro|hu|gr|sk|bg|hr|si|lt|lv|ee|is|mt|lu|li|mc|sm|va|ad|al|ba|mk|me|rs|tr|ua|by|kz|uz|am|ge|az|tm|kg|tj|md|kg|tj|af|dz|bh|eg|iq|ir|jo|kw|lb|ly|ma|om|ps|qa|sa|sd|sy|tn|ae|ye|ar|bo|br|cl|co|ec|gf|gy|pe|py|sr|uy|ve|ag|ai|aw|bb|bm|bs|bz|ca|cr|cu|dm|do|gd|gp|gt|hn|ht|jm|kn|ky|lc|ms|mx|ni|pa|pr|sv|tc|tt|vc|vg|vi|an|aq|as|fj|fm|gu|hm|id|ki|mh|mp|nc|nf|nr|nu|pf|pg|pw|sb|tk|to|tv|vu|wf|ws)(?:\/[a-zA-Z0-9._~:\/?#[\]@!$&'()*+,;=-]*)?)(?:\s)/),f=new RegExp(/(?:https?:\/\/)(?:www\.)?([А-Яа-яa-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.(?:ru|com|org|net|me|su|рф|biz|info|co|uk|de|fr|jp|cn|es|it|ca|au|nl|se|no|dk|fi|pl|at|ch|be|cz|ie|pt|ro|hu|gr|sk|bg|hr|si|lt|lv|ee|is|mt|lu|li|mc|sm|va|ad|al|ba|mk|me|rs|tr|ua|by|kz|uz|am|ge|az|tm|kg|tj|md|kg|tj|af|dz|bh|eg|iq|ir|jo|kw|lb|ly|ma|om|ps|qa|sa|sd|sy|tn|ae|ye|ar|bo|br|cl|co|ec|gf|gy|pe|py|sr|uy|ve|ag|ai|aw|bb|bm|bs|bz|ca|cr|cu|dm|do|gd|gp|gt|hn|ht|jm|kn|ky|lc|ms|mx|ni|pa|pr|sv|tc|tt|vc|vg|vi|an|aq|as|fj|fm|gu|hm|id|ki|mh|mp|nc|nf|nr|nu|pf|pg|pw|sb|tk|to|tv|vu|wf|ws)(?:\/[a-zA-Z0-9._~:\/?#[\]@!$&'()*+,;=-]*)?)(?:\s)/),l=t=>t;function p(t,e){return e.split(".").reduce(((t,e)=>t?t[e]:void 0),t)}const g=t=>{const e=t.toString(16);return 1==e.length?"0"+e:e};exports.HEXtoRGB=t=>{if(3===(t=t.replace("#","")).length&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),6!==t.length)return[0,0,0];const e=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),n=parseInt(t.substring(4,6),16);return isNaN(e)||isNaN(r)||isNaN(n)||e<0||e>255||r<0||r>255||n<0||n>255?[0,0,0]:[e,r,n]},exports.HSVtoRGB=(t,e,r)=>{var n,o,s,c,a,i,u,f;switch(i=r*(1-e),u=r*(1-(a=6*t-(c=Math.floor(6*t)))*e),f=r*(1-(1-a)*e),c%6){case 0:n=r,o=f,s=i;break;case 1:n=u,o=r,s=i;break;case 2:n=i,o=r,s=f;break;case 3:n=i,o=u,s=r;break;case 4:n=f,o=i,s=r;break;case 5:n=r,o=i,s=u}return[Math.round(255*n),Math.round(255*o),Math.round(255*s)]},exports.RGBtoHEX=(t,e,r)=>"#"+g(t)+g(e)+g(r),exports.RGBtoHSV=(t,e,r)=>{var n=Math.max(t,e,r),o=Math.min(t,e,r),s=n-o,c=0,a=0===n?0:s/n,i=n/255;switch(n){case o:c=0;break;case t:c=e-r+s*(e<r?6:0),c/=6*s;break;case e:c=r-t+2*s,c/=6*s;break;case r:c=t-e+4*s,c/=6*s}return[c,a,i]},exports.alignTo=function(t,e){return t<=0?e:t+(e-t%e)%e},exports.chunks=(t,e)=>{const r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r},exports.clamp=(t,e,r)=>t>e?t<r?t:r:e,exports.comparison=n,exports.copyText=t=>{if(!t)return!1;try{return navigator.clipboard?.writeText(t),!0}catch{}try{var e=document.createElement("input");return e.value=t,document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),!0}catch{}return!1},exports.createLinksFromText=(t,e)=>{const r=[],n=/{{([^}]+):([^}]+)}}/g;let o,s=0;for(;null!==(o=n.exec(t));)r.push(t.substring(s,o.index)),s=o.index+o[0].length,r.push({key:o[1],text:o[2]});return r.push(t.substring(s)),r.map((t=>"string"==typeof t?t:e(t.key,t.text)))},exports.decWord=t,exports.formatNumber=t=>(t||0).toString().replace(/\B(?=(\d{3})+(?!\d))/g,"."),exports.generateUniqueKey=t=>{const e=t=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t||null===t)return JSON.stringify(t);if(Array.isArray(t))return"["+t.map(e).join(",")+"]";if("object"==typeof t){const r=Object.keys(t).sort();let n="{";for(let o=0;o<r.length;o++){const s=r[o];n+=JSON.stringify(s)+":"+e(t[s]),o<r.length-1&&(n+=",")}return n+="}",n}return String(t)},r=t=>{let e=0;if(0===t.length)return e;for(let r=0;r<t.length;r++){e=(e<<5)-e+t.charCodeAt(r),e|=0}return e};try{const n=e(t);return r(n).toString(16)}catch(e){return console.warn(`Object could not be fully stringified. Using a simple string conversion. Error: ${e}`),r(String(t)).toString(16)}},exports.groupBy=function(t,e){return t.reduce(((t,r)=>{const n=e(r);return t[n]||(t[n]=[]),t[n].push(r),t}),{})},exports.isType=function(t,e){for(const[n,o]of Object.entries(r))if(o(t))return void 0!==e?n===e:n;return void 0===e&&"unknown"},exports.memoize=function(t){const e=new Map;return function(...r){const n=JSON.stringify(r);if(e.has(n))return e.get(n);const o=t(...r);return e.set(n,o),o}},exports.omit=function(t,e){return Object.keys(t).reduce(((r,n)=>(e.includes(n)||(r[n]=t[n]),r)),{})},exports.orderBy=function(t,e){const r=Object.keys(e);return t.slice().sort(((t,n)=>{for(const o of r){const r="desc"===e[o]?-1:1,s=p(t,o),c=p(n,o);if(s<c)return-r;if(s>c)return r}return 0}))},exports.parseQueryString=function(t){const e={},r=(t.startsWith("?")?t.slice(1):t).split("&");for(const t of r){const[r,n]=t.split("=");if(r){const t=decodeURIComponent(r),o=n?decodeURIComponent(n):"";e[t]=o}}return e},exports.pick=function(t,e){return Object.keys(t).reduce(((r,n)=>(e.includes(n)&&(r[n]=t[n]),r)),{})},exports.random=e,exports.randomByWeight=function(t,r){let n=0;for(const e in t)n+=t[e];const o=e(0,n,r);let s=0;for(const e in t)if(s+=t[e],o<s)return e;const c=Object.keys(t);return c[e(0,c.length-1,r)]},exports.retry=function(t,e,r){return new Promise(((n,o)=>{const s=e=>{t().then(n).catch((t=>{0===e?o(t):(console.log(`Retrying... attempts left: ${e}`),setTimeout((()=>s(e-1)),r))}))};s(e)}))},exports.shuffle=(t,r)=>{for(let n=t.length-1;n>0;n--){const o=e(0,n,r);[t[n],t[o]]=[t[o],t[n]]}return t},exports.sleep=async t=>await new Promise((e=>setTimeout(e,t))),exports.textParserUrl=(t,e)=>{const r=e?.onToken??l,n=e?.requireProtocol??!1,o=e?.regex??n?f:u,s=[];let c=t+" ",a=o.exec(c);for(;a;){const t=a[0].trim(),e=a.index;e>0&&(s.push(r({type:"raw",value:c.substring(0,e)})),c=c.substring(e)),s.push(r({type:"url",value:t})),c=c.substring(t.length),a=o.exec(c)}return c.length>0&&s.push(r({type:"raw",value:c})),s},exports.timeAgo=e=>{if(!e)return"только что";const r=new Date(e),n=Math.floor((Date.now()-r.getTime())/1e3),o=()=>new Intl.DateTimeFormat("RU-ru",{day:"numeric",month:"short"}).format(r).replace(".",""),s=()=>r.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),c=(e,r,n)=>Array.isArray(e)?`${n} ${t(n,e)} ${r}`:`${e} ${r}`;switch(!0){case n<0:return"скоро";case n<60:return c(["секунду","секунды","секунд"],"назад",n);case n<3600:return c(["минуту","минуты","минут"],"назад",Math.floor(n/60));case n<7200:return c("час","назад",Math.floor(n/3600));case n<10800:return c("два часа","назад",Math.floor(n/3600));case n<14400:return c("три часа","назад",Math.floor(n/3600));case n<86400:return c(`сегодня в ${s()}`,"",Math.floor(n/3600));case n<172800:return c(`вчера в ${s()}`,"",Math.floor(n/86400));case n<259200:return c("два дня","назад",Math.floor(n/86400));case n<345600:return c("три дня","назад",Math.floor(n/86400));case n<31536e3:return c(`${o()} в ${s()}`,"",Math.floor(n/86400));case n>=31536e3:return c(`${o()} ${r.getFullYear()} г.`,"",Math.floor(n/31536e3))}return"только что"},exports.toShort=(t,e,r=1)=>{const n=e||["","k","M","G","T","P"],o=t<0,s=Math.abs(t),c=Math.log10(s)/3|0,a=s/10**(3*c);return parseFloat(`${o?"-":""}${a%1?(Math.floor(10*a)/10).toFixed(r):a}`)+n[c]},exports.unique=function(t){return Array.from(new Set(t))},exports.unlink=t=>{switch(s(t)){case"[object Array]":return a(t);case"[object Object]":return i(t);default:return c(t)}};
package/index.mjs CHANGED
@@ -1 +1 @@
1
- const e=(e,t)=>{const r=[];for(let n=0;n<t.length;n+=e)r.push(t.slice(n,n+e));return r},t=(e,t,r)=>e>t?e<r?e:r:t,r=(e,t)=>t[e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2];function n(e,t){return e<=0?t:e+(t-e%t)%t}const o=(e,t,r=1)=>{const n=t||["","k","M","G","T","P"],o=e<0,a=Math.abs(e),s=Math.log10(a)/3|0,c=a/10**(3*s);return parseFloat(`${o?"-":""}${c%1?(Math.floor(10*c)/10).toFixed(r):c}`)+n[s]},a=e=>{if(!e)return"только что";const t=new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3),o=()=>new Intl.DateTimeFormat("RU-ru",{day:"numeric",month:"short"}).format(t).replace(".",""),a=()=>t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),s=(e,t,n)=>Array.isArray(e)?`${n} ${r(n,e)} ${t}`:`${e} ${t}`;switch(!0){case n<0:return"скоро";case n<60:return s(["секунду","секунды","секунд"],"назад",n);case n<3600:return s(["минуту","минуты","минут"],"назад",Math.floor(n/60));case n<7200:return s("час","назад",Math.floor(n/3600));case n<10800:return s("два часа","назад",Math.floor(n/3600));case n<14400:return s("три часа","назад",Math.floor(n/3600));case n<86400:return s(`сегодня в ${a()}`,"",Math.floor(n/3600));case n<172800:return s(`вчера в ${a()}`,"",Math.floor(n/86400));case n<259200:return s("два дня","назад",Math.floor(n/86400));case n<345600:return s("три дня","назад",Math.floor(n/86400));case n<31536e3:return s(`${o()} в ${a()}`,"",Math.floor(n/86400));case n>=31536e3:return s(`${o()} ${t.getFullYear()} г.`,"",Math.floor(n/31536e3))}return"только что"},s=e=>(e||0).toString().replace(/\B(?=(\d{3})+(?!\d))/g,"."),c=e=>{for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}return e},i=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),u={date:e=>e instanceof Date,regexp:e=>e instanceof RegExp,error:e=>e instanceof Error,map:e=>e instanceof Map,set:e=>e instanceof Set,weakmap:e=>e instanceof WeakMap,weakset:e=>e instanceof WeakSet,promise:e=>e instanceof Promise,buffer:e=>e instanceof Buffer,undefined:e=>void 0===e,string:e=>"string"==typeof e,bigint:e=>"bigint"==typeof e,number:e=>"number"==typeof e&&!isNaN(e),nan:e=>"number"==typeof e&&isNaN(e),boolean:e=>"boolean"==typeof e,array:e=>Array.isArray(e),object:e=>"object"==typeof e&&!Array.isArray(e)&&null!==e,function:e=>"function"==typeof e,null:e=>null===e,symbol:e=>"symbol"==typeof e,unknown:()=>!0};function l(e,t){for(const[r,n]of Object.entries(u))if(n(e))return void 0!==t?r===t:r;return void 0===t&&"unknown"}function f(e,t){return Object.keys(e).reduce(((r,n)=>(t.includes(n)||(r[n]=e[n]),r)),{})}function b(e,t){return Object.keys(e).reduce(((r,n)=>(t.includes(n)&&(r[n]=e[n]),r)),{})}const g=async e=>await new Promise((t=>setTimeout(t,e))),p=e=>{if(!e)return!1;try{return navigator.clipboard?.writeText(e),!0}catch{}try{var t=document.createElement("input");return t.value=e,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),!0}catch{}return!1},h=(e,t)=>{const r=[],n=/{{([^}]+):([^}]+)}}/g;let o,a=0;for(;null!==(o=n.exec(e));)r.push(e.substring(a,o.index)),a=o.index+o[0].length,r.push({key:o[1],text:o[2]});return r.push(e.substring(a)),r.map((e=>"string"==typeof e?e:t(e.key,e.text)))},m=(e,t)=>{if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return e===t;if("[object Map]"===Object.prototype.toString.call(e)&&"[object Map]"===Object.prototype.toString.call(t))return y(e,t);const r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(let n of r){if(!t.hasOwnProperty(n))return!1;const r=e[n],o=t[n];if(Array.isArray(r)&&Array.isArray(o)){if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++)if(!m(r[e],o[e]))return!1}else if(!m(r,o))return!1}return!0},y=(e,t)=>{if(e.size!==t.size)return!1;for(const[r,n]of e){if(!t.has(r))return!1;if(!m(t.get(r),n))return!1}return!0},d=e=>{const t=e=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e||null===e)return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(t).join(",")+"]";if("object"==typeof e){const r=Object.keys(e).sort();let n="{";for(let o=0;o<r.length;o++){const a=r[o];n+=JSON.stringify(a)+":"+t(e[a]),o<r.length-1&&(n+=",")}return n+="}",n}return String(e)},r=e=>{let t=0;if(0===e.length)return t;for(let r=0;r<e.length;r++){t=(t<<5)-t+e.charCodeAt(r),t|=0}return t};try{const n=t(e);return r(n).toString(16)}catch(t){return console.warn(`Object could not be fully stringified. Using a simple string conversion. Error: ${t}`),r(String(e)).toString(16)}},k=e=>Object.prototype.toString.call(e),j=(e,t)=>{switch(t||k(t)){case"[object Number]":return Number(String(e));case"[object String]":return String(e);case"[object BigInt]":return BigInt(String(e));case"[object Map]":return new Map(e);case"[object Set]":return new Set(e);default:return e}},w=e=>{const t=[];for(const r of e){const e=k(r);"[object Array]"===e?t.push(w(r)):"[object Object]"===e?t.push(v(r)):t.push(j(r))}return t},v=e=>{const t={},r=Object.keys(e);for(const n of r){const r=k(e[n]);t[n]="[object Array]"===r?w(e[n]):"[object Object]"===r?v(e[n]):e[n]}return t},M=e=>{switch(k(e)){case"[object Array]":return w(e);case"[object Object]":return v(e);default:return j(e)}},z=new RegExp(/(?:https?:\/\/)?(?:www\.)?([А-Яа-яa-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.(?:ru|com|org|net|me|su|рф|biz|info|co|uk|de|fr|jp|cn|es|it|ca|au|nl|se|no|dk|fi|pl|at|ch|be|cz|ie|pt|ro|hu|gr|sk|bg|hr|si|lt|lv|ee|is|mt|lu|li|mc|sm|va|ad|al|ba|mk|me|rs|tr|ua|by|kz|uz|am|ge|az|tm|kg|tj|md|kg|tj|af|dz|bh|eg|iq|ir|jo|kw|lb|ly|ma|om|ps|qa|sa|sd|sy|tn|ae|ye|ar|bo|br|cl|co|ec|gf|gy|pe|py|sr|uy|ve|ag|ai|aw|bb|bm|bs|bz|ca|cr|cu|dm|do|gd|gp|gt|hn|ht|jm|kn|ky|lc|ms|mx|ni|pa|pr|sv|tc|tt|vc|vg|vi|an|aq|as|fj|fm|gu|hm|id|ki|mh|mp|nc|nf|nr|nu|pf|pg|pw|sb|tk|to|tv|vu|wf|ws)(?:\/[a-zA-Z0-9._~:\/?#[\]@!$&'()*+,;=-]*)?)(?:\s)/),A=new RegExp(/(?:https?:\/\/)(?:www\.)?([А-Яа-яa-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.(?:ru|com|org|net|me|su|рф|biz|info|co|uk|de|fr|jp|cn|es|it|ca|au|nl|se|no|dk|fi|pl|at|ch|be|cz|ie|pt|ro|hu|gr|sk|bg|hr|si|lt|lv|ee|is|mt|lu|li|mc|sm|va|ad|al|ba|mk|me|rs|tr|ua|by|kz|uz|am|ge|az|tm|kg|tj|md|kg|tj|af|dz|bh|eg|iq|ir|jo|kw|lb|ly|ma|om|ps|qa|sa|sd|sy|tn|ae|ye|ar|bo|br|cl|co|ec|gf|gy|pe|py|sr|uy|ve|ag|ai|aw|bb|bm|bs|bz|ca|cr|cu|dm|do|gd|gp|gt|hn|ht|jm|kn|ky|lc|ms|mx|ni|pa|pr|sv|tc|tt|vc|vg|vi|an|aq|as|fj|fm|gu|hm|id|ki|mh|mp|nc|nf|nr|nu|pf|pg|pw|sb|tk|to|tv|vu|wf|ws)(?:\/[a-zA-Z0-9._~:\/?#[\]@!$&'()*+,;=-]*)?)(?:\s)/),x=e=>e,S=(e,t)=>{const r=t?.onToken??x,n=t?.requireProtocol??!1,o=t?.regex??n?A:z,a=[];let s=e+" ",c=o.exec(s);for(;c;){const e=c[0].trim(),t=c.index;t>0&&(a.push(r({type:"raw",value:s.substring(0,t)})),s=s.substring(t)),a.push(r({type:"url",value:e})),s=s.substring(e.length),c=o.exec(s)}return s.length>0&&a.push(r({type:"raw",value:s})),a},O=(e,t,r)=>{var n,o,a,s,c,i,u,l;switch(i=r*(1-t),u=r*(1-(c=6*e-(s=Math.floor(6*e)))*t),l=r*(1-(1-c)*t),s%6){case 0:n=r,o=l,a=i;break;case 1:n=u,o=r,a=i;break;case 2:n=i,o=r,a=l;break;case 3:n=i,o=u,a=r;break;case 4:n=l,o=i,a=r;break;case 5:n=r,o=i,a=u}return[Math.round(255*n),Math.round(255*o),Math.round(255*a)]},$=e=>{const t=e.toString(16);return 1==t.length?"0"+t:t},N=(e,t,r)=>"#"+$(e)+$(t)+$(r),T=(e,t,r)=>{var n=Math.max(e,t,r),o=Math.min(e,t,r),a=n-o,s=0,c=0===n?0:a/n,i=n/255;switch(n){case o:s=0;break;case e:s=t-r+a*(t<r?6:0),s/=6*a;break;case t:s=r-e+2*a,s/=6*a;break;case r:s=e-t+4*a,s/=6*a}return[s,c,i]},q=e=>{if(3===(e=e.replace("#","")).length&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),6!==e.length)return[0,0,0];const t=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),n=parseInt(e.substring(4,6),16);return isNaN(t)||isNaN(r)||isNaN(n)||t<0||t>255||r<0||r>255||n<0||n>255?[0,0,0]:[t,r,n]};export{q as HEXtoRGB,O as HSVtoRGB,N as RGBtoHEX,T as RGBtoHSV,n as alignTo,e as chunks,t as clamp,m as comparison,p as copyText,h as createLinksFromText,r as decWord,s as formatNumber,d as generateUniqueKey,l as isType,f as omit,b as pick,i as random,c as shuffle,g as sleep,S as textParserUrl,a as timeAgo,o as toShort,M as unlink};
1
+ const t=(t,e)=>{const r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r},e=(t,e,r)=>t>e?t<r?t:r:e,r=(t,e)=>e[t%10==1&&t%100!=11?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2];function n(t,e){return t<=0?e:t+(e-t%e)%e}const o=(t,e,r=1)=>{const n=e||["","k","M","G","T","P"],o=t<0,s=Math.abs(t),c=Math.log10(s)/3|0,a=s/10**(3*c);return parseFloat(`${o?"-":""}${a%1?(Math.floor(10*a)/10).toFixed(r):a}`)+n[c]},s=t=>{if(!t)return"только что";const e=new Date(t),n=Math.floor((Date.now()-e.getTime())/1e3),o=()=>new Intl.DateTimeFormat("RU-ru",{day:"numeric",month:"short"}).format(e).replace(".",""),s=()=>e.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),c=(t,e,n)=>Array.isArray(t)?`${n} ${r(n,t)} ${e}`:`${t} ${e}`;switch(!0){case n<0:return"скоро";case n<60:return c(["секунду","секунды","секунд"],"назад",n);case n<3600:return c(["минуту","минуты","минут"],"назад",Math.floor(n/60));case n<7200:return c("час","назад",Math.floor(n/3600));case n<10800:return c("два часа","назад",Math.floor(n/3600));case n<14400:return c("три часа","назад",Math.floor(n/3600));case n<86400:return c(`сегодня в ${s()}`,"",Math.floor(n/3600));case n<172800:return c(`вчера в ${s()}`,"",Math.floor(n/86400));case n<259200:return c("два дня","назад",Math.floor(n/86400));case n<345600:return c("три дня","назад",Math.floor(n/86400));case n<31536e3:return c(`${o()} в ${s()}`,"",Math.floor(n/86400));case n>=31536e3:return c(`${o()} ${e.getFullYear()} г.`,"",Math.floor(n/31536e3))}return"только что"},c=t=>(t||0).toString().replace(/\B(?=(\d{3})+(?!\d))/g,".");function a(t,e,r){if(!r){const t=new Date;r=t.getDate()*t.getFullYear()*(t.getHours()??1)*t.getMilliseconds()}const n=function(t){const e=2**32;let r=t;return function(){var t;return r=(1664525*r+1013904223)%e,t=r,t^=t>>>21,r=(t^=t<<35)^t>>>4,(r>>>0)/e}}(r);return function(t,e,r){if(e>r)throw new Error("Минимальная граница не может быть больше максимальной.");return Math.floor(t()*(r-e+1))+e}(n,t,e)}const u=(t,e)=>{for(let r=t.length-1;r>0;r--){const n=a(0,r,e);[t[r],t[n]]=[t[n],t[r]]}return t};function i(t,e){let r=0;for(const e in t)r+=t[e];const n=a(0,r,e);let o=0;for(const e in t)if(o+=t[e],n<o)return e;const s=Object.keys(t);return s[a(0,s.length-1,e)]}const f={date:t=>t instanceof Date,regexp:t=>t instanceof RegExp,error:t=>t instanceof Error,map:t=>t instanceof Map,set:t=>t instanceof Set,weakmap:t=>t instanceof WeakMap,weakset:t=>t instanceof WeakSet,promise:t=>t instanceof Promise,buffer:t=>t instanceof Buffer,undefined:t=>void 0===t,string:t=>"string"==typeof t,bigint:t=>"bigint"==typeof t,number:t=>"number"==typeof t&&!isNaN(t),nan:t=>"number"==typeof t&&isNaN(t),boolean:t=>"boolean"==typeof t,array:t=>Array.isArray(t),object:t=>"object"==typeof t&&!Array.isArray(t)&&null!==t,function:t=>"function"==typeof t,null:t=>null===t,symbol:t=>"symbol"==typeof t,unknown:()=>!0};function l(t,e){for(const[r,n]of Object.entries(f))if(n(t))return void 0!==e?r===e:r;return void 0===e&&"unknown"}function g(t,e){return Object.keys(t).reduce(((r,n)=>(e.includes(n)||(r[n]=t[n]),r)),{})}function p(t,e){return Object.keys(t).reduce(((r,n)=>(e.includes(n)&&(r[n]=t[n]),r)),{})}const b=async t=>await new Promise((e=>setTimeout(e,t))),h=t=>{if(!t)return!1;try{return navigator.clipboard?.writeText(t),!0}catch{}try{var e=document.createElement("input");return e.value=t,document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),!0}catch{}return!1},m=(t,e)=>{const r=[],n=/{{([^}]+):([^}]+)}}/g;let o,s=0;for(;null!==(o=n.exec(t));)r.push(t.substring(s,o.index)),s=o.index+o[0].length,r.push({key:o[1],text:o[2]});return r.push(t.substring(s)),r.map((t=>"string"==typeof t?t:e(t.key,t.text)))},y=(t,e)=>{if(t===e)return!0;if("object"!=typeof t||null===t||"object"!=typeof e||null===e)return t===e;if("[object Map]"===Object.prototype.toString.call(t)&&"[object Map]"===Object.prototype.toString.call(e))return d(t,e);const r=Object.keys(t);if(r.length!==Object.keys(e).length)return!1;for(let n of r){if(!e.hasOwnProperty(n))return!1;const r=t[n],o=e[n];if(Array.isArray(r)&&Array.isArray(o)){if(r.length!==o.length)return!1;for(let t=0;t<r.length;t++)if(!y(r[t],o[t]))return!1}else if(!y(r,o))return!1}return!0},d=(t,e)=>{if(t.size!==e.size)return!1;for(const[r,n]of t){if(!e.has(r))return!1;if(!y(e.get(r),n))return!1}return!0},k=t=>{const e=t=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t||null===t)return JSON.stringify(t);if(Array.isArray(t))return"["+t.map(e).join(",")+"]";if("object"==typeof t){const r=Object.keys(t).sort();let n="{";for(let o=0;o<r.length;o++){const s=r[o];n+=JSON.stringify(s)+":"+e(t[s]),o<r.length-1&&(n+=",")}return n+="}",n}return String(t)},r=t=>{let e=0;if(0===t.length)return e;for(let r=0;r<t.length;r++){e=(e<<5)-e+t.charCodeAt(r),e|=0}return e};try{const n=e(t);return r(n).toString(16)}catch(e){return console.warn(`Object could not be fully stringified. Using a simple string conversion. Error: ${e}`),r(String(t)).toString(16)}},j=t=>Object.prototype.toString.call(t),w=(t,e)=>{switch(e||j(e)){case"[object Number]":return Number(String(t));case"[object String]":return String(t);case"[object BigInt]":return BigInt(String(t));case"[object Map]":return new Map(t);case"[object Set]":return new Set(t);default:return t}},v=t=>{const e=[];for(const r of t){const t=j(r);"[object Array]"===t?e.push(v(r)):"[object Object]"===t?e.push(M(r)):e.push(w(r))}return e},M=t=>{const e={},r=Object.keys(t);for(const n of r){const r=j(t[n]);e[n]="[object Array]"===r?v(t[n]):"[object Object]"===r?M(t[n]):t[n]}return e},A=t=>{switch(j(t)){case"[object Array]":return v(t);case"[object Object]":return M(t);default:return w(t)}},z=new RegExp(/(?:https?:\/\/)?(?:www\.)?([А-Яа-яa-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.(?:ru|com|org|net|me|su|рф|biz|info|co|uk|de|fr|jp|cn|es|it|ca|au|nl|se|no|dk|fi|pl|at|ch|be|cz|ie|pt|ro|hu|gr|sk|bg|hr|si|lt|lv|ee|is|mt|lu|li|mc|sm|va|ad|al|ba|mk|me|rs|tr|ua|by|kz|uz|am|ge|az|tm|kg|tj|md|kg|tj|af|dz|bh|eg|iq|ir|jo|kw|lb|ly|ma|om|ps|qa|sa|sd|sy|tn|ae|ye|ar|bo|br|cl|co|ec|gf|gy|pe|py|sr|uy|ve|ag|ai|aw|bb|bm|bs|bz|ca|cr|cu|dm|do|gd|gp|gt|hn|ht|jm|kn|ky|lc|ms|mx|ni|pa|pr|sv|tc|tt|vc|vg|vi|an|aq|as|fj|fm|gu|hm|id|ki|mh|mp|nc|nf|nr|nu|pf|pg|pw|sb|tk|to|tv|vu|wf|ws)(?:\/[a-zA-Z0-9._~:\/?#[\]@!$&'()*+,;=-]*)?)(?:\s)/),S=new RegExp(/(?:https?:\/\/)(?:www\.)?([А-Яа-яa-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.(?:ru|com|org|net|me|su|рф|biz|info|co|uk|de|fr|jp|cn|es|it|ca|au|nl|se|no|dk|fi|pl|at|ch|be|cz|ie|pt|ro|hu|gr|sk|bg|hr|si|lt|lv|ee|is|mt|lu|li|mc|sm|va|ad|al|ba|mk|me|rs|tr|ua|by|kz|uz|am|ge|az|tm|kg|tj|md|kg|tj|af|dz|bh|eg|iq|ir|jo|kw|lb|ly|ma|om|ps|qa|sa|sd|sy|tn|ae|ye|ar|bo|br|cl|co|ec|gf|gy|pe|py|sr|uy|ve|ag|ai|aw|bb|bm|bs|bz|ca|cr|cu|dm|do|gd|gp|gt|hn|ht|jm|kn|ky|lc|ms|mx|ni|pa|pr|sv|tc|tt|vc|vg|vi|an|aq|as|fj|fm|gu|hm|id|ki|mh|mp|nc|nf|nr|nu|pf|pg|pw|sb|tk|to|tv|vu|wf|ws)(?:\/[a-zA-Z0-9._~:\/?#[\]@!$&'()*+,;=-]*)?)(?:\s)/),x=t=>t,O=(t,e)=>{const r=e?.onToken??x,n=e?.requireProtocol??!1,o=e?.regex??n?S:z,s=[];let c=t+" ",a=o.exec(c);for(;a;){const t=a[0].trim(),e=a.index;e>0&&(s.push(r({type:"raw",value:c.substring(0,e)})),c=c.substring(e)),s.push(r({type:"url",value:t})),c=c.substring(t.length),a=o.exec(c)}return c.length>0&&s.push(r({type:"raw",value:c})),s};function $(t){const e=new Map;return function(...r){const n=JSON.stringify(r);if(e.has(n))return e.get(n);const o=t(...r);return e.set(n,o),o}}function N(t,e,r){return new Promise(((n,o)=>{const s=e=>{t().then(n).catch((t=>{0===e?o(t):(console.log(`Retrying... attempts left: ${e}`),setTimeout((()=>s(e-1)),r))}))};s(e)}))}function T(t){return Array.from(new Set(t))}function I(t){const e={},r=(t.startsWith("?")?t.slice(1):t).split("&");for(const t of r){const[r,n]=t.split("=");if(r){const t=decodeURIComponent(r),o=n?decodeURIComponent(n):"";e[t]=o}}return e}function q(t,e){return t.reduce(((t,r)=>{const n=e(r);return t[n]||(t[n]=[]),t[n].push(r),t}),{})}function E(t,e){return e.split(".").reduce(((t,e)=>t?t[e]:void 0),t)}function R(t,e){const r=Object.keys(e);return t.slice().sort(((t,n)=>{for(const o of r){const r="desc"===e[o]?-1:1,s=E(t,o),c=E(n,o);if(s<c)return-r;if(s>c)return r}return 0}))}const C=(t,e,r)=>{var n,o,s,c,a,u,i,f;switch(u=r*(1-e),i=r*(1-(a=6*t-(c=Math.floor(6*t)))*e),f=r*(1-(1-a)*e),c%6){case 0:n=r,o=f,s=u;break;case 1:n=i,o=r,s=u;break;case 2:n=u,o=r,s=f;break;case 3:n=u,o=i,s=r;break;case 4:n=f,o=u,s=r;break;case 5:n=r,o=u,s=i}return[Math.round(255*n),Math.round(255*o),Math.round(255*s)]},D=t=>{const e=t.toString(16);return 1==e.length?"0"+e:e},P=(t,e,r)=>"#"+D(t)+D(e)+D(r),Z=(t,e,r)=>{var n=Math.max(t,e,r),o=Math.min(t,e,r),s=n-o,c=0,a=0===n?0:s/n,u=n/255;switch(n){case o:c=0;break;case t:c=e-r+s*(e<r?6:0),c/=6*s;break;case e:c=r-t+2*s,c/=6*s;break;case r:c=t-e+4*s,c/=6*s}return[c,a,u]},F=t=>{if(3===(t=t.replace("#","")).length&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),6!==t.length)return[0,0,0];const e=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),n=parseInt(t.substring(4,6),16);return isNaN(e)||isNaN(r)||isNaN(n)||e<0||e>255||r<0||r>255||n<0||n>255?[0,0,0]:[e,r,n]};export{F as HEXtoRGB,C as HSVtoRGB,P as RGBtoHEX,Z as RGBtoHSV,n as alignTo,t as chunks,e as clamp,y as comparison,h as copyText,m as createLinksFromText,r as decWord,c as formatNumber,k as generateUniqueKey,q as groupBy,l as isType,$ as memoize,g as omit,R as orderBy,I as parseQueryString,p as pick,a as random,i as randomByWeight,N as retry,u as shuffle,b as sleep,O as textParserUrl,s as timeAgo,o as toShort,T as unique,A as unlink};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@minsize/utils",
3
- "version": "0.0.15",
3
+ "version": "0.0.17",
4
4
  "description": "Frequently used utilities",
5
5
  "license": "MIT",
6
6
  "types": "index.ts",