forked from fp-toolkit/fp-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
String.ts
109 lines (95 loc) · 2.27 KB
/
String.ts
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
/**
* The string module is a suite of functions that are useful for string manipulation and
* properly, designed for seamless use in function composition pipelines.
*
* @module String
*/
import type { NonEmptyArray } from "../NonEmptyArray"
/**
* A boolean check that also serves as a type guard which narrows the
* type to the string literal `""`.
*
* @group Utils
* @group Type Guards
*
* @returns boolean
*/
export const isEmpty = (s: string): s is "" => s === ""
/**
* Curried version of the built-in trim method.
*
* @group Utils
*/
export const trim = (s: string) => s.trim()
/**
* Curried version of the built-in toLowerCase method.
*
* @group Utils
*/
export const toLowerCase = (s: string) => s.toLowerCase()
/**
* Curried version of the built-in toUpperCase method.
*
* @group Utils
*/
export const toUpperCase = (s: string) => s.toUpperCase()
/**
* Type guard that holds true when `u` is a string.
*
* @group Type Guards
*
* @returns boolean
*/
export const isString = (u: unknown): u is string => typeof u === "string"
/**
* Get the length of a string.
*
* @group Utils
*/
export const length = (s: string) => s.length
/**
* Reverses a string.
*
* @group Utils
*/
export const reverse = (s: string) => s.split("").reverse().join("")
/**
* A curried version of the built-in split method that
* is guaranteed to always return at least one entry. If
* the split fails to produce at least one entry, the entire
* input string is returned as a single-element array.
*
* @group Utils
*/
export const split =
(separator: string | RegExp) =>
(s: string): NonEmptyArray<string> => {
const result = s.split(separator)
return result.length > 0
? (result as unknown as NonEmptyArray<string>)
: [s]
}
/**
* Capitalize the first letter of a string.
*
* @group Utils
*/
export const capitalize = (s: string) => {
if (s.length < 1) {
return ""
}
const [head, ...tail] = s.split("")
return [head.toUpperCase(), ...tail].join("")
}
/**
* Uncapitalize the first letter of a string.
*
* @group Utils
*/
export const uncapitalize = (s: string) => {
if (s.length < 1) {
return ""
}
const [head, ...tail] = s.split("")
return [head.toLowerCase(), ...tail].join("")
}