@ooneex/utils 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +335 -0
  2. package/index.d.ts +69 -0
  3. package/index.js +1 -0
  4. package/package.json +19 -0
package/README.md ADDED
@@ -0,0 +1,335 @@
1
+ # @ooneex/utils
2
+
3
+ A comprehensive collection of utility functions for common programming tasks including string manipulation, number formatting, time conversion, and more.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @ooneex/utils
9
+ # or
10
+ bun add @ooneex/utils
11
+ # or
12
+ yarn add @ooneex/utils
13
+ # or
14
+ pnpm add @ooneex/utils
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```typescript
20
+ import { capitalizeWord, formatRelativeNumber, random, sleep, dataURLtoFile } from '@ooneex/utils';
21
+ ```
22
+
23
+ ## API Reference
24
+
25
+ ### File Utilities
26
+
27
+ #### `dataURLtoFile(dataurl: string, filename: string): File`
28
+
29
+ Converts a data URL string into a File object, useful for handling base64-encoded file data.
30
+
31
+ **Examples:**
32
+ ```typescript
33
+ import { dataURLtoFile } from '@ooneex/utils';
34
+
35
+ // Convert a data URL to a File object
36
+ const dataUrl = 'data:text/plain;base64,SGVsbG8gV29ybGQ=';
37
+ const file = dataURLtoFile(dataUrl, 'hello.txt');
38
+
39
+ // Use with image data URLs
40
+ const imageDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB...';
41
+ const imageFile = dataURLtoFile(imageDataUrl, 'image.png');
42
+
43
+ // The resulting File object can be used in FormData or uploaded
44
+ const formData = new FormData();
45
+ formData.append('file', file);
46
+ ```
47
+
48
+ ### String Utilities
49
+
50
+ #### `capitalizeWord(word: string): string`
51
+
52
+ Capitalizes the first letter of a word and makes the rest lowercase.
53
+
54
+ **Examples:**
55
+ ```typescript
56
+ import { capitalizeWord } from '@ooneex/utils';
57
+
58
+ capitalizeWord('hello'); // 'Hello'
59
+ capitalizeWord('WORLD'); // 'World'
60
+ capitalizeWord('javaScript'); // 'Javascript'
61
+ capitalizeWord(''); // ''
62
+ ```
63
+
64
+ #### `splitToWords(input: string): string[]`
65
+
66
+ Splits a string into an array of words, handling camelCase, PascalCase, kebab-case, snake_case, and more.
67
+
68
+ **Examples:**
69
+ ```typescript
70
+ import { splitToWords } from '@ooneex/utils';
71
+
72
+ splitToWords('helloWorld'); // ['hello', 'World']
73
+ splitToWords('PascalCaseString'); // ['Pascal', 'Case', 'String']
74
+ splitToWords('kebab-case-string'); // ['kebab', 'case', 'string']
75
+ splitToWords('snake_case_string'); // ['snake', 'case', 'string']
76
+ splitToWords('HTMLElement123'); // ['HTML', 'Element', '123']
77
+ splitToWords('URLParser'); // ['URL', 'Parser']
78
+ ```
79
+
80
+ #### `toCamelCase(input: string): string`
81
+
82
+ Converts a string to camelCase.
83
+
84
+ **Examples:**
85
+ ```typescript
86
+ import { toCamelCase } from '@ooneex/utils';
87
+
88
+ toCamelCase('hello world'); // 'helloWorld'
89
+ toCamelCase('PascalCaseString'); // 'pascalCaseString'
90
+ toCamelCase('kebab-case-string'); // 'kebabCaseString'
91
+ toCamelCase('snake_case_string'); // 'snakeCaseString'
92
+ toCamelCase(' SPACED STRING '); // 'spacedString'
93
+ ```
94
+
95
+ #### `toPascalCase(input: string): string`
96
+
97
+ Converts a string to PascalCase.
98
+
99
+ **Examples:**
100
+ ```typescript
101
+ import { toPascalCase } from '@ooneex/utils';
102
+
103
+ toPascalCase('hello world'); // 'HelloWorld'
104
+ toPascalCase('camelCaseString'); // 'CamelCaseString'
105
+ toPascalCase('kebab-case-string'); // 'KebabCaseString'
106
+ toPascalCase('snake_case_string'); // 'SnakeCaseString'
107
+ toPascalCase(' spaced string '); // 'SpacedString'
108
+ ```
109
+
110
+ #### `toKebabCase(input: string): string`
111
+
112
+ Converts a string to kebab-case.
113
+
114
+ **Examples:**
115
+ ```typescript
116
+ import { toKebabCase } from '@ooneex/utils';
117
+
118
+ toKebabCase('Hello World'); // 'hello-world'
119
+ toKebabCase('camelCaseString'); // 'camel-case-string'
120
+ toKebabCase('PascalCaseString'); // 'pascal-case-string'
121
+ toKebabCase('snake_case_string'); // 'snake-case-string'
122
+ toKebabCase(' SPACED STRING '); // 'spaced-string'
123
+ ```
124
+
125
+ #### `trim(text: string, char?: string): string`
126
+
127
+ Trims specified characters from the beginning and end of a string. Defaults to trimming whitespace.
128
+
129
+ **Examples:**
130
+ ```typescript
131
+ import { trim } from '@ooneex/utils';
132
+
133
+ trim(' hello world '); // 'hello world'
134
+ trim('...hello world...', '.'); // 'hello world'
135
+ trim('[hello world]', '['); // 'hello world]'
136
+ trim('[hello world]', '\\[|\\]'); // 'hello world'
137
+ trim('***hello world***', '*'); // 'hello world'
138
+ ```
139
+
140
+ ### Parsing Utilities
141
+
142
+ #### `parseString<T = unknown>(text: string): T`
143
+
144
+ Intelligently parses a string into appropriate JavaScript types (number, boolean, array, object, etc.).
145
+
146
+ **Examples:**
147
+ ```typescript
148
+ import { parseString } from '@ooneex/utils';
149
+
150
+ parseString('123'); // 123 (number)
151
+ parseString('45.67'); // 45.67 (number)
152
+ parseString('true'); // true (boolean)
153
+ parseString('false'); // false (boolean)
154
+ parseString('null'); // null
155
+ parseString('[1, 2, 3]'); // [1, 2, 3] (array)
156
+ parseString('{"key": "value"}'); // { key: "value" } (object)
157
+ parseString('hello'); // 'hello' (string)
158
+ parseString('[apple, banana, 123]'); // ['apple', 'banana', 123]
159
+ ```
160
+
161
+ #### `parseEnvVars<T = Record<string, unknown>>(envs: Record<string, unknown>): T`
162
+
163
+ Parses environment variables, converting keys to camelCase and values to appropriate types.
164
+
165
+ **Examples:**
166
+ ```typescript
167
+ import { parseEnvVars } from '@ooneex/utils';
168
+
169
+ const envVars = {
170
+ 'DATABASE_URL': 'postgresql://localhost:5432/db',
171
+ 'PORT': '3000',
172
+ 'ENABLE_LOGGING': 'true',
173
+ 'MAX_CONNECTIONS': '100'
174
+ };
175
+
176
+ const parsed = parseEnvVars(envVars);
177
+ // {
178
+ // databaseUrl: 'postgresql://localhost:5432/db',
179
+ // port: 3000,
180
+ // enableLogging: true,
181
+ // maxConnections: 100
182
+ // }
183
+ ```
184
+
185
+ ### Number Formatting
186
+
187
+ #### `formatRelativeNumber(num: number, config?: { precision?: number; lang?: string }): string`
188
+
189
+ Formats numbers using compact notation (K, M, B, etc.).
190
+
191
+ **Examples:**
192
+ ```typescript
193
+ import { formatRelativeNumber } from '@ooneex/utils';
194
+
195
+ formatRelativeNumber(1234); // '1.2K'
196
+ formatRelativeNumber(1234567); // '1.2M'
197
+ formatRelativeNumber(1234567890); // '1.2B'
198
+ formatRelativeNumber(1234, { precision: 0 }); // '1K'
199
+ formatRelativeNumber(1234, { precision: 2 }); // '1.23K'
200
+ formatRelativeNumber(1234, { lang: 'de' }); // '1,2 Tsd.'
201
+ formatRelativeNumber(1500000, { lang: 'fr' }); // '1,5 M'
202
+ ```
203
+
204
+ ### Time Conversion
205
+
206
+ #### `millisecondsToHMS(ms: number): string`
207
+
208
+ Converts milliseconds to HH:MM:SS or MM:SS format.
209
+
210
+ **Examples:**
211
+ ```typescript
212
+ import { millisecondsToHMS } from '@ooneex/utils';
213
+
214
+ millisecondsToHMS(30000); // '30'
215
+ millisecondsToHMS(90000); // '1:30'
216
+ millisecondsToHMS(3661000); // '1:01:01'
217
+ millisecondsToHMS(45000); // '45'
218
+ millisecondsToHMS(125000); // '2:05'
219
+ millisecondsToHMS(7323000); // '2:02:03'
220
+ ```
221
+
222
+ #### `secondsToHMS(seconds: number): string`
223
+
224
+ Converts seconds to HH:MM:SS or MM:SS format.
225
+
226
+ **Examples:**
227
+ ```typescript
228
+ import { secondsToHMS } from '@ooneex/utils';
229
+
230
+ secondsToHMS(30); // '30'
231
+ secondsToHMS(90); // '1:30'
232
+ secondsToHMS(3661); // '1:01:01'
233
+ secondsToHMS(45); // '45'
234
+ secondsToHMS(125); // '2:05'
235
+ secondsToHMS(7323); // '2:02:03'
236
+ ```
237
+
238
+ #### `secondsToMS(seconds: number): string`
239
+
240
+ Converts seconds to MM:SS format.
241
+
242
+ **Examples:**
243
+ ```typescript
244
+ import { secondsToMS } from '@ooneex/utils';
245
+
246
+ secondsToMS(30); // '0:30'
247
+ secondsToMS(90); // '1:30'
248
+ secondsToMS(125); // '2:05'
249
+ secondsToMS(3661); // '61:01'
250
+ ```
251
+
252
+ ### Random Generation
253
+
254
+ #### `random`
255
+
256
+ Object containing various random string generation functions.
257
+
258
+ **Examples:**
259
+ ```typescript
260
+ import { random } from '@ooneex/utils';
261
+
262
+ // Generate random hexadecimal string (default 10 characters)
263
+ random.nanoid(); // 'a1b2c3d4e5'
264
+ random.nanoid(5); // '1a2b3'
265
+ random.nanoid(16); // '1234567890abcdef'
266
+
267
+ // Generate random numeric string
268
+ random.stringInt(); // '1234567890'
269
+ random.stringInt(5); // '12345'
270
+
271
+ // Create a factory function for consistent length
272
+ const generateId = random.nanoidFactory(8);
273
+ generateId(); // 'a1b2c3d4'
274
+ generateId(); // '5e6f7890'
275
+ ```
276
+
277
+ ### Async Utilities
278
+
279
+ #### `sleep(ms: number): Promise<void>`
280
+
281
+ Creates a promise that resolves after the specified number of milliseconds, useful for adding delays in async functions.
282
+
283
+ **Examples:**
284
+ ```typescript
285
+ import { sleep } from '@ooneex/utils';
286
+
287
+ // Wait for 1 second
288
+ await sleep(1000);
289
+
290
+ // Use in async function
291
+ async function delayedOperation() {
292
+ console.log('Starting...');
293
+ await sleep(2000); // Wait 2 seconds
294
+ console.log('Done!');
295
+ }
296
+
297
+ // Use with other async operations
298
+ async function retryWithDelay() {
299
+ for (let i = 0; i < 3; i++) {
300
+ try {
301
+ await someOperation();
302
+ break;
303
+ } catch (error) {
304
+ if (i < 2) await sleep(1000); // Wait 1 second before retry
305
+ }
306
+ }
307
+ }
308
+ ```
309
+
310
+ ## Type Safety
311
+
312
+ All functions are fully typed with TypeScript, providing excellent IDE support and compile-time type checking.
313
+
314
+ ```typescript
315
+ // Generic type support
316
+ const parsedNumber = parseString<number>('123'); // Type: number
317
+ const parsedArray = parseString<string[]>('[a,b,c]'); // Type: string[]
318
+
319
+ // Environment variables with custom type
320
+ interface AppConfig {
321
+ port: number;
322
+ databaseUrl: string;
323
+ enableLogging: boolean;
324
+ }
325
+
326
+ const config = parseEnvVars<AppConfig>(process.env);
327
+ ```
328
+
329
+ ## License
330
+
331
+ MIT
332
+
333
+ ## Contributing
334
+
335
+ Contributions are welcome! Please feel free to submit a Pull Request.
package/index.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ declare module "capitalizeWord" {
2
+ export const capitalizeWord: (word: string) => string;
3
+ }
4
+ declare module "dataURLtoFile" {
5
+ export const dataURLtoFile: (dataurl: string, filename: string) => File;
6
+ }
7
+ declare module "formatRelativeNumber" {
8
+ export const formatRelativeNumber: (num: number, config?: {
9
+ precision?: number;
10
+ lang?: string;
11
+ }) => string;
12
+ }
13
+ declare module "millisecondsToHMS" {
14
+ export const millisecondsToHMS: (ms: number) => string;
15
+ }
16
+ declare module "trim" {
17
+ export const trim: (text: string, char?: string) => string;
18
+ }
19
+ declare module "parseString" {
20
+ export const parseString: <T = unknown>(text: string) => T;
21
+ }
22
+ declare module "splitToWords" {
23
+ export const splitToWords: (input: string) => RegExpMatchArray | [];
24
+ }
25
+ declare module "toCamelCase" {
26
+ export const toCamelCase: (input: string) => string;
27
+ }
28
+ declare module "parseEnvVars" {
29
+ export const parseEnvVars: <T = Record<string, unknown>>(envs: Record<string, unknown>) => T;
30
+ }
31
+ declare module "random" {
32
+ export const random: {
33
+ nanoid(size?: number): string;
34
+ stringInt(size?: number): string;
35
+ nanoidFactory(size?: number): (size?: number) => string;
36
+ };
37
+ }
38
+ declare module "secondsToHMS" {
39
+ export const secondsToHMS: (seconds: number) => string;
40
+ }
41
+ declare module "secondsToMS" {
42
+ export const secondsToMS: (seconds: number) => string;
43
+ }
44
+ declare module "sleep" {
45
+ export const sleep: (ms: number) => Promise<void>;
46
+ }
47
+ declare module "toKebabCase" {
48
+ export const toKebabCase: (input: string) => string;
49
+ }
50
+ declare module "toPascalCase" {
51
+ export const toPascalCase: (input: string) => string;
52
+ }
53
+ declare module "index" {
54
+ export { capitalizeWord } from "capitalizeWord";
55
+ export { dataURLtoFile } from "dataURLtoFile";
56
+ export { formatRelativeNumber } from "formatRelativeNumber";
57
+ export { millisecondsToHMS } from "millisecondsToHMS";
58
+ export { parseEnvVars } from "parseEnvVars";
59
+ export { parseString } from "parseString";
60
+ export { random } from "random";
61
+ export { secondsToHMS } from "secondsToHMS";
62
+ export { secondsToMS } from "secondsToMS";
63
+ export { sleep } from "sleep";
64
+ export { splitToWords } from "splitToWords";
65
+ export { toCamelCase } from "toCamelCase";
66
+ export { toKebabCase } from "toKebabCase";
67
+ export { toPascalCase } from "toPascalCase";
68
+ export { trim } from "trim";
69
+ }
package/index.js ADDED
@@ -0,0 +1 @@
1
+ var i=(r)=>{return r?r[0]?.toUpperCase()+r.slice(1).toLowerCase():r};var g=(r,t)=>{let o=r.split(","),n=o[0]?.match(/:(.*?);/),e=n?n[1]:"",l=atob(o[1]),a=l.length,f=new Uint8Array(a);while(a--)f[a]=l.charCodeAt(a);return new File([f],t,{type:e})};var d=(r,t)=>{return new Intl.NumberFormat(t?.lang??"en-GB",{notation:"compact",compactDisplay:"short",maximumFractionDigits:t?.precision??1}).format(r)};var S=(r)=>{let t=Math.floor(r/1000),o=Math.floor(t/3600),n=Math.floor(t%3600/60),e=t%60;if(o>0)return`${o}:${n.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`;if(n>0)return`${n}:${e.toString().padStart(2,"0")}`;return e.toString()};var p=(r,t=" ")=>{if([".","[","]","(",")","+","*","^","$","?","/","\\"].includes(t))t=`\\${t}`;let o=new RegExp(`^${t}+|${t}+$`,"g");return r.replace(o,"")};var m=(r)=>{if(/^[0-9]+$/.test(r))return Number.parseInt(r,10);if(/^[0-9]+[.][0-9]+$/.test(r))return Number.parseFloat(r);if(/^true$/i.test(r))return!0;if(/^false$/i.test(r))return!1;if(/^null$/i.test(r))return null;if(/^\[/.test(r)&&/]$/.test(r)){let o=p(r,"\\[|\\]").split(/, */);return o=o.map((n)=>{return m(n)}),o}try{let t=JSON.parse(r);if(t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY)return r;return t}catch{return r}};var b=/\p{Lu}\p{Ll}+/u,T=/\p{Lu}+(?=(\p{Lu}\p{Ll})|\P{L}|\b)/u,$=/(\p{Ll}+)/u,x=/\p{L}+/u,C=/\p{N}+/u,M=new RegExp(`${b.source}|${T.source}|${$.source}|${x.source}|${C.source}`,"gu"),s=(r)=>{return r.match(M)??[]};var c=(r)=>{r=r.trim();let[t="",...o]=s(r);return[t.toLowerCase(),...o.map(i)].join("")};var h=(r)=>{let t={};for(let o in r){let n=c(o),e=m(r[o]);t[n]=e}return t};import{customAlphabet as u}from"nanoid";var N={nanoid(r){return u("1234567890abcdef",r??10)()},stringInt(r){return u("1234567890",r??10)()},nanoidFactory(r){return u("1234567890abcdef",r??10)}};var w=(r)=>{let t=Math.floor(r),o=Math.floor(t/3600),n=Math.floor(t%3600/60),e=t%60;if(o>0)return`${o}:${n.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`;if(n>0)return`${n}:${e.toString().padStart(2,"0")}`;return e.toString()};var F=(r)=>{let t=Math.floor(r/60),o=r%60;return`${t}:${o.toString().padStart(2,"0")}`};var k=(r)=>{return new Promise((t)=>setTimeout(t,r))};var I=(r)=>{return r=r.trim(),s(r).join("-").toLowerCase()};var v=(r)=>{return r=r.trim(),s(r).map(i).join("")};export{p as trim,v as toPascalCase,I as toKebabCase,c as toCamelCase,s as splitToWords,k as sleep,F as secondsToMS,w as secondsToHMS,N as random,m as parseString,h as parseEnvVars,S as millisecondsToHMS,d as formatRelativeNumber,g as dataURLtoFile,i as capitalizeWord};
package/package.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "@ooneex/utils",
3
+ "version": "0.0.3",
4
+ "description": "",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "type": "module",
8
+ "license": "MIT",
9
+ "scripts": {
10
+ "compile": "tsc ./src/index.ts --declaration --emitDeclarationOnly --target ES2022 --moduleResolution bundler --outfile dist/index.d.ts",
11
+ "build": "rm -rf dist && bun run compile && bun build ./src/index.ts --outdir ./dist --target browser --format esm --packages external --minify",
12
+ "publish": "bun run build && cp package.json dist && cp README.md dist && cd dist && bun publish --access public"
13
+ },
14
+ "devDependencies": {},
15
+ "peerDependencies": {},
16
+ "dependencies": {
17
+ "nanoid": "^5.1.6"
18
+ }
19
+ }