-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathstringUtils.ts
More file actions
78 lines (72 loc) · 2.28 KB
/
Copy pathstringUtils.ts
File metadata and controls
78 lines (72 loc) · 2.28 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
// Assuming input string is following the HTTP Cookie format defined in
// https://www.ietf.org/rfc/rfc2616.txt and https://www.ietf.org/rfc/rfc6265.txt, we don't need to
// be too strict with this regex.
const COMMA_SEPARATED_KEY_VALUE = /(\S+?)\s*=\s*(.*?)(?:;|$)/g
/**
* Returns the value of the key with the given name
* If there are multiple values with the same key, returns the first one
*/
export function findCommaSeparatedValue(rawString: string, name: string): string | undefined {
COMMA_SEPARATED_KEY_VALUE.lastIndex = 0
while (true) {
const match = COMMA_SEPARATED_KEY_VALUE.exec(rawString)
if (match) {
if (match[1] === name) {
return match[2]
}
} else {
break
}
}
}
/**
* Returns a map of all the values with the given key
* If there are multiple values with the same key, returns all the values
*/
export function findAllCommaSeparatedValues(rawString: string): Map<string, string[]> {
const result = new Map<string, string[]>()
COMMA_SEPARATED_KEY_VALUE.lastIndex = 0
while (true) {
const match = COMMA_SEPARATED_KEY_VALUE.exec(rawString)
if (match) {
const key = match[1]
const value = match[2]
if (result.has(key)) {
result.get(key)!.push(value)
} else {
result.set(key, [value])
}
} else {
break
}
}
return result
}
/**
* Returns a map of the values with the given key
* ⚠️ If there are multiple values with the same key, returns the LAST one
*
* @deprecated use `findAllCommaSeparatedValues()` instead
*/
export function findCommaSeparatedValues(rawString: string): Map<string, string> {
const result = new Map<string, string>()
COMMA_SEPARATED_KEY_VALUE.lastIndex = 0
while (true) {
const match = COMMA_SEPARATED_KEY_VALUE.exec(rawString)
if (match) {
result.set(match[1], match[2])
} else {
break
}
}
return result
}
export function safeTruncate(candidate: string, length: number, suffix = '') {
const lastChar = candidate.charCodeAt(length - 1)
const isLastCharSurrogatePair = lastChar >= 0xd800 && lastChar <= 0xdbff
const correctedLength = isLastCharSurrogatePair ? length + 1 : length
if (candidate.length <= correctedLength) {
return candidate
}
return `${candidate.slice(0, correctedLength)}${suffix}`
}