-
Notifications
You must be signed in to change notification settings - Fork 113
/
strings.ts
83 lines (75 loc) · 2.08 KB
/
strings.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export function startsWith(haystack: string, needle: string): boolean {
if (haystack.length < needle.length) {
return false;
}
for (let i = 0; i < needle.length; i++) {
if (haystack[i] !== needle[i]) {
return false;
}
}
return true;
}
/**
* Determines if haystack ends with needle.
*/
export function endsWith(haystack: string, needle: string): boolean {
const diff = haystack.length - needle.length;
if (diff > 0) {
return haystack.lastIndexOf(needle) === diff;
} else if (diff === 0) {
return haystack === needle;
} else {
return false;
}
}
export function convertSimple2RegExpPattern(pattern: string): string {
return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
}
export function repeat(value: string, count: number) {
let s = '';
while (count > 0) {
if ((count & 1) === 1) {
s += value;
}
value += value;
count = count >>> 1;
}
return s;
}
export function extendedRegExp(pattern: string): RegExp | undefined {
let flags = '';
if (startsWith(pattern, '(?i)')) {
pattern = pattern.substring(4);
flags = 'i';
}
try {
return new RegExp(pattern, flags + 'u');
} catch (e) {
// could be an exception due to the 'u ' flag
try {
return new RegExp(pattern, flags);
} catch (e) {
// invalid pattern
return undefined;
}
}
}
// from https://tanishiking.github.io/posts/count-unicode-codepoint/#work-hard-with-for-statements
export function stringLength(str: string) {
let count = 0;
for (let i = 0; i < str.length; i++) {
count++;
// obtain the i-th 16-bit
const code = str.charCodeAt(i);
if (0xD800 <= code && code <= 0xDBFF) {
// if the i-th 16bit is an upper surrogate
// skip the next 16 bits (lower surrogate)
i++;
}
}
return count;
}