forked from OKEAMAH/prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathskip.js
More file actions
69 lines (62 loc) · 1.9 KB
/
skip.js
File metadata and controls
69 lines (62 loc) · 1.9 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
/**
* @typedef {{backwards?: boolean}} SkipOptions
*/
/**
* @param {string | RegExp} characters
* @returns {(text: string, startIndex: number | false, options?: SkipOptions) => number | false}
*/
function skip(characters) {
return (text, startIndex, options) => {
const backwards = Boolean(options?.backwards);
// Allow `skip` functions to be threaded together without having
// to check for failures (did someone say monads?).
/* c8 ignore next 3 */
if (startIndex === false) {
return false;
}
const { length } = text;
let cursor = startIndex;
while (cursor >= 0 && cursor < length) {
const character = text.charAt(cursor);
if (characters instanceof RegExp) {
if (!characters.test(character)) {
return cursor;
}
} else if (!characters.includes(character)) {
return cursor;
}
backwards ? cursor-- : cursor++;
}
if (cursor === -1 || cursor === length) {
// If we reached the beginning or end of the file, return the
// out-of-bounds cursor. It's up to the caller to handle this
// correctly. We don't want to indicate `false` though if it
// actually skipped valid characters.
return cursor;
}
return false;
};
}
/**
* @type {(text: string, startIndex: number | false, options?: SkipOptions) => number | false}
*/
const skipWhitespace = skip(/\s/u);
/**
* @type {(text: string, startIndex: number | false, options?: SkipOptions) => number | false}
*/
const skipSpaces = skip(" \t");
/**
* @type {(text: string, startIndex: number | false, options?: SkipOptions) => number | false}
*/
const skipToLineEnd = skip(",; \t");
/**
* @type {(text: string, startIndex: number | false, options?: SkipOptions) => number | false}
*/
const skipEverythingButNewLine = skip(/[^\n\r]/u);
export {
skip,
skipEverythingButNewLine,
skipSpaces,
skipToLineEnd,
skipWhitespace,
};