-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.js
90 lines (76 loc) · 1.76 KB
/
utils.js
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
'use strict';
/**
* Removes tokens that matches given criteria from start and end of given list
* @param {Token[]} tokens
* @return {Token[]}
*/
export function trimTokens(tokens) {
tokens = tokens.slice();
let len;
while (len !== tokens.length) {
len = tokens.length;
if (isFormattingToken(tokens[0])) {
tokens.shift();
}
if (isFormattingToken(last(tokens))) {
tokens.pop();
}
}
return tokens;
}
/**
* Trims formatting tokens (whitespace and comments) from the beginning and end
* of given token list
* @param {Token[]} tokens
* @return {Token[]}
*/
export function trimFormatting(tokens) {
return trimTokens(tokens, isFormattingToken);
}
/**
* Check if given token is a formatting one (whitespace or comment)
* @param {Token} token
* @return {Boolean}
*/
export function isFormattingToken(token) {
const type = token && token.type;
return type === 'whitespace' || type === 'comment';
}
/**
* Consumes string char-by-char from given stream
* @param {StreamReader} stream
* @param {String} string
* @return {Boolean} Returns `true` if string was completely consumed
*/
export function eatString(stream, string) {
const start = stream.pos;
for (let i = 0, il = string.length; i < il; i++) {
if (!stream.eat(string.charCodeAt(i))) {
stream.pos = start;
return false;
}
}
return true;
}
export function consume(stream, match) {
const start = stream.pos;
if (stream.eat(match)) {
stream.start = start;
return true;
}
return false;
}
export function consumeWhile(stream, match) {
const start = stream.pos;
if (stream.eatWhile(match)) {
stream.start = start;
return true;
}
return false;
}
export function last(arr) {
return arr[arr.length - 1];
}
export function valueOf(token) {
return token && token.valueOf();
}