-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
72 lines (57 loc) · 1.87 KB
/
utils.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
// Copyright 2023-latest the httpland authors. All rights reserved. MIT license.
// This module is browser compatible.
import { escapeStringRegExp, isToken } from "./deps.ts";
export function duplicate<T>(list: readonly T[]): T[] {
const duplicates = new Set<T>();
list.forEach((value, index) => {
if (list.indexOf(value) !== index) {
duplicates.add(value);
}
});
return [...duplicates];
}
/**
* ```abnf
* token68 = 1*( ALPHA / DIGIT /
* "-" / "." / "_" / "~" / "+" / "/" ) *"="
* ```
*/
const reToken68 = /^[\w.~+/-]+?=*?$/;
/** Whether the input is [token68](https://www.rfc-editor.org/rfc/rfc9110.html#section-11.2-2) or not. */
export function isToken68(input: string): boolean {
return reToken68.test(input);
}
/** Assert the input is [token68](https://www.rfc-editor.org/rfc/rfc9110.html#section-11.2-2). */
export function assertToken68(
input: string,
msg?: string,
constructor: ErrorConstructor = Error,
): asserts input {
if (!isToken68(input)) throw new constructor(msg);
}
/** Assert the input is [token](https://www.rfc-editor.org/rfc/rfc9110.html#section-5.6.2-2). */
export function assertToken(
input: string,
msg?: string,
constructor: ErrorConstructor = Error,
): asserts input {
if (!isToken(input)) throw new constructor(msg);
}
/** Divide two string. The first string is matched, second string is rest. */
export function divideWhile(
input: string,
match: (input: string) => boolean,
): [matched: string, rest: string] | null {
let matched = "";
for (const str of input) {
if (!match(str)) break;
matched += str;
}
if (!matched) return null;
const rest = input.slice(matched.length);
return [matched, rest];
}
/** Trim start by something. */
export function trimStartBy(input: string, separator: string): string {
return input.replace(new RegExp(`^${escapeStringRegExp(separator)}+`), "");
}