-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwords.ts
More file actions
69 lines (65 loc) · 1.95 KB
/
words.ts
File metadata and controls
69 lines (65 loc) · 1.95 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
/**
* @fileoverview Word manipulation utilities for capitalization and formatting.
* Provides text transformation functions for consistent word processing.
*/
export interface PluralizeOptions {
count?: number
}
/**
* Capitalize the first letter of a word.
*
* @example
* ```typescript
* capitalize('hello') // 'Hello'
* capitalize('WORLD') // 'World'
* capitalize('') // ''
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function capitalize(word: string): string {
if (word.length === 0) {
return word
}
// Iterate by code point, not UTF-16 unit, so non-BMP characters
// (emoji, astral-plane scripts) aren't split between their surrogate
// pair halves. `charAt(0).toUpperCase() + slice(1).toLowerCase()` used
// to produce broken surrogate pairs for inputs like '𐐀foo'.
const [first, ...rest] = [...word]
return (first ?? '').toUpperCase() + rest.join('').toLowerCase()
}
/**
* Determine the appropriate article (a/an) for a word.
*
* @example
* ```typescript
* determineArticle('apple') // 'an'
* determineArticle('banana') // 'a'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function determineArticle(word: string): string {
// Case-insensitive so `Apple` and `apple` both pick `an`. Strict
// spelling rules can't handle silent-h / y-sound exceptions (hour,
// user); documenting that as a known limitation rather than shipping
// a multi-entry exception list.
return /^[aeiou]/i.test(word) ? 'an' : 'a'
}
/**
* Pluralize a word based on count.
*
* @example
* ```typescript
* pluralize('file') // 'file'
* pluralize('file', { count: 3 }) // 'files'
* pluralize('file', { count: 0 }) // 'files'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function pluralize(
word: string,
options?: PluralizeOptions | undefined,
): string {
const { count = 1 } = { __proto__: null, ...options } as PluralizeOptions
// Handle 0, negatives, decimals, and values > 1 as plural.
return count === 1 ? word : `${word}s`
}