-
Notifications
You must be signed in to change notification settings - Fork 250
Expand file tree
/
Copy pathstring.ts
More file actions
455 lines (422 loc) · 11 KB
/
string.ts
File metadata and controls
455 lines (422 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
import {takeRandomFromArray} from './array.js'
import {unstyled} from '../../public/node/output.js'
import {Token, TokenItem} from '../../private/node/ui/components/TokenizedText.js'
import {camelCase, capitalCase, constantCase, paramCase, snakeCase, pascalCase} from 'change-case'
const SAFE_RANDOM_BUSINESS_ADJECTIVES = [
'commercial',
'profitable',
'amortizable',
'branded',
'integrated',
'synergistic',
'consolidated',
'diversified',
'lean',
'niche',
'premium',
'luxury',
'scalable',
'optimized',
'empowered',
'international',
'beneficial',
'fruitful',
'extensive',
'lucrative',
'modern',
'stable',
'strategic',
'adaptive',
'efficient',
'growing',
'sustainable',
'innovative',
'regional',
'specialized',
'focused',
'pragmatic',
'ethical',
'flexible',
'competitive',
]
const SAFE_RANDOM_CREATIVE_ADJECTIVES = [
'bright',
'impactful',
'stylish',
'colorful',
'modern',
'minimal',
'trendy',
'creative',
'artistic',
'spectacular',
'glamorous',
'luxury',
'retro',
'nostalgic',
'comfy',
'polished',
'fabulous',
'balanced',
'monochrome',
'glitched',
'contrasted',
'elegant',
'textured',
'vibrant',
'harmonious',
'versatile',
'eclectic',
'futuristic',
'idealistic',
'intricate',
'bohemian',
'abstract',
'meticulous',
'refined',
'flamboyant',
]
const SAFE_RANDOM_BUSINESS_NOUNS = [
'account',
'consumer',
'customer',
'enterprise',
'business',
'venture',
'marketplace',
'revenue',
'vertical',
'portfolio',
'negotiation',
'shipping',
'demand',
'supply',
'growth',
'merchant',
'investment',
'shareholder',
'conversion',
'capital',
'projection',
'upside',
'trade',
'deal',
'merchandise',
'transaction',
'sale',
'franchise',
'subsidiary',
'logistics',
'sponsorship',
'partnership',
'tax',
'policy',
'outsource',
'equity',
'strategy',
'valuation',
'benchmark',
'metrics',
'duplication',
]
const SAFE_RANDOM_CREATIVE_NOUNS = [
'vibe',
'style',
'moment',
'mood',
'flavor',
'look',
'appearance',
'perspective',
'aspect',
'ambience',
'quality',
'backdrop',
'focus',
'tone',
'inspiration',
'imagery',
'aesthetics',
'palette',
'ornamentation',
'contrast',
'colorway',
'visuals',
'typography',
'composition',
'scale',
'symmetry',
'gradients',
'proportions',
'textures',
'harmony',
'shapes',
'patterns',
]
export type RandomNameFamily = 'business' | 'creative'
/**
* Generates a random name by combining an adjective and noun.
*
* @param family - Theme to use for the random name (business or creative).
* @returns A random name generated by combining an adjective and noun.
*/
export function getRandomName(family: RandomNameFamily = 'business'): string {
const mapping = {
business: {
adjectives: SAFE_RANDOM_BUSINESS_ADJECTIVES,
nouns: SAFE_RANDOM_BUSINESS_NOUNS,
},
creative: {
adjectives: SAFE_RANDOM_CREATIVE_ADJECTIVES,
nouns: SAFE_RANDOM_CREATIVE_NOUNS,
},
}
return `${takeRandomFromArray(mapping[family].adjectives)}-${takeRandomFromArray(mapping[family].nouns)}`
}
/**
* Given a string, it returns it with the first letter capitalized.
*
* @param str - String to capitalize.
* @returns String with the first letter capitalized.
*/
export function capitalize(str: string): string {
return str.substring(0, 1).toUpperCase() + str.substring(1)
}
/**
* Given a list of items, it returns a pluralized string based on the amount of items.
*
* @param items - List of items.
* @param plural - Supplier used when the list of items has more than one item.
* @param singular - Supplier used when the list of items has a single item.
* @param none - Supplier used when the list has no items.
* @returns The {@link TokenItem} supplied by the {@link plural}, {@link singular}, or {@link none} functions.
*/
export function pluralize<
T,
TToken extends Token = Token,
TPluralToken extends TToken = TToken,
TSingularToken extends TToken = TToken,
TNoneToken extends TToken = TToken,
>(
items: T[],
plural: (items: T[]) => TokenItem<TPluralToken>,
singular: (item: T) => TokenItem<TSingularToken>,
none?: () => TokenItem<TNoneToken>,
): TokenItem<TPluralToken | TSingularToken | TNoneToken> | string {
if (items.length === 1) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return singular(items[0]!)
}
if (items.length > 1) {
return plural(items)
}
if (none) {
return none()
}
return ''
}
/**
* Try to convert a string to an int, falling back to undefined if unable to.
*
* @param maybeInt - String to convert to an int.
* @returns The int if it was able to convert, otherwise undefined.
*/
export function tryParseInt(maybeInt: string | undefined): number | undefined {
let asInt: number | undefined
if (maybeInt !== undefined) {
asInt = parseInt(maybeInt, 10)
if (isNaN(asInt)) {
asInt = undefined
}
}
return asInt
}
/**
* Transforms a matrix of strings into a single string with the columns aligned.
*
* @param lines - Array of rows, where each row is an array of strings (representing columns).
* @returns A string with the columns aligned.
*/
export function linesToColumns(lines: string[][]): string {
const widths: number[] = []
for (let i = 0; lines[0] && i < lines[0].length; i++) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const columnRows = lines.map((line) => line[i]!)
widths.push(Math.max(...columnRows.map((row) => unstyled(row).length)))
}
const paddedLines = lines
.map((line) => {
return line
.map((col, index) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return `${col}${' '.repeat(widths[index]! - unstyled(col).length)}`
})
.join(' ')
.trimEnd()
})
.join('\n')
return paddedLines
}
/**
* Given a string, it transforms it to a slug (lowercase, hyphenated, no special chars, trimmed...).
*
* @param str - String to slugify.
* @returns The slugified string.
*/
export function slugify(str: string): string {
return str
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '')
.replace(/[\s_-]+/g, '-')
.replace(/^-+|-+$/g, '')
}
/**
* Given a string, it returns it with the special regex characters escaped.
* More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping.
*
* @param str - String to escape.
* @returns The escaped string.
*/
export function escapeRegExp(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
/**
* Transform a string to camelCase.
*
* @param input - String to escape.
* @returns The escaped string.
*/
export function camelize(input: string): string {
return camelCase(input)
}
/**
* Transform a string to capitalCase.
*
* @param input - String to transform.
* @returns The transformed string.
*/
export function capitalizeWords(input: string): string {
return capitalCase(input)
}
/**
* Transform a string to param-case.
*
* @param input - String to transform.
* @returns The transformed string.
*/
export function hyphenate(input: string): string {
return paramCase(input)
}
/**
* Transform a string to snake_case.
*
* @param input - String to transform.
* @returns The transformed string.
*/
export function underscore(input: string): string {
return snakeCase(input)
}
/**
* Transform a string to CONSTANT_CASE.
*
* @param input - String to transform.
* @returns The transformed string.
*/
export function constantize(input: string): string {
return constantCase(input)
}
/**
* Given a date, return a formatted string like "2021-01-01 12:00:00".
*
* @param date - Date to format.
* @returns The transformed string.
*/
export function formatDate(date: Date): string {
const components = date.toISOString().split('T')
const dateString = components[0] ?? date.toDateString()
const timeString = components[1]?.split('.')[0] ?? date.toTimeString()
return `${dateString} ${timeString}`
}
/**
* Given a date in UTC ISO String format, return a formatted string in local time like "2021-01-01 12:00:00".
*
* @param dateString - UTC ISO Date String.
* @returns The transformed string in local system time.
*/
export function formatLocalDate(dateString: string): string {
const dateObj = new Date(dateString)
const localDate = new Date(
Date.UTC(
dateObj.getFullYear(),
dateObj.getMonth(),
dateObj.getDate(),
dateObj.getHours(),
dateObj.getMinutes(),
dateObj.getSeconds(),
),
)
return formatDate(localDate)
}
/**
* Given a list of items, it returns a string with the items joined by commas and the last item joined by "and".
* All items are wrapped in double quotes.
* For example: ["a", "b", "c"] returns "a", "b" and "c".
*
* @param items - List of items.
* @returns The joined string.
*/
export function joinWithAnd(items: string[]): string {
if (items.length === 0) return ''
if (items.length === 1) return `"${items[0]}"`
return `${items
.slice(0, -1)
.map((item) => `"${item}"`)
.join(', ')} and "${items[items.length - 1]}"`
}
/**
* Given a string, it returns the PascalCase form of it.
* Eg: "pascal_case" returns "PascalCase".
*
* @param str - String to PascalCase.
* @returns String with all the first letter capitalized with no spaces.
*/
export function pascalize(str: string): string {
return pascalCase(str)
}
/**
* Given a string that represents a list of delimited tokens, it returns the normalized string representing the same
* list, without empty elements, sorted, and with no duplicates.
*
* @param delimitedString - String to normalize.
* @param delimiter - Delimiter used to split the string into tokens.
* @returns String with the normalized list of tokens.
*/
export function normalizeDelimitedString(delimitedString?: string, delimiter = ','): string | undefined {
if (!delimitedString) return
const items = delimitedString.split(delimiter).map((value) => value.trim())
const nonEmptyItems = items.filter((value) => value !== '')
const sortedItems = nonEmptyItems.sort()
const uniqueSortedItems = [...new Set(sortedItems)]
return uniqueSortedItems.join(delimiter)
}
/**
* Given two dates, it returns a human-readable string representing the time elapsed between them.
*
* @param from - Start date.
* @param to - End date.
* @returns A string like "5 minutes ago" or "2 days ago".
*/
export function timeAgo(from: Date, to: Date): string {
const seconds = Math.floor((to.getTime() - from.getTime()) / 1000)
if (seconds < 60) return `${formatTimeUnit(seconds, 'second')} ago`
const minutes = Math.floor(seconds / 60)
if (minutes < 60) return `${formatTimeUnit(minutes, 'minute')} ago`
const hours = Math.floor(minutes / 60)
if (hours < 24) return `${formatTimeUnit(hours, 'hour')} ago`
const days = Math.floor(hours / 24)
return `${formatTimeUnit(days, 'day')} ago`
}
function formatTimeUnit(count: number, unit: string): string {
return `${count} ${unit}${count === 1 ? '' : 's'}`
}