-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsplitter.js
62 lines (61 loc) · 1.56 KB
/
splitter.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
/**
* Text splitter that also returns character position. Functionally
* equivalent to string.split, but faster.
* @param {string} text - The text to split.
* @param {string} ch - The character on which to split.
* @returns A splitter that can be used to iteratively call `next()` for
* each part.
*/
function Splitter(text, ch) {
let start = 0;
let pos = ch ? text.indexOf(ch) : 0;
return {
/**
* Returns the next split.
* @returns The text an character index of the split `{ text, pos }`,
* or `null` when done.
*/
next: function _split() {
if (text.length === 0) {
return null;
} else if (!ch) {
if (start >= text.length) {
return null;
}
const part = {
text: text.charAt(start),
pos: start
};
start += 1;
return part;
} else if (pos < 0) {
// handle remaining text. the `start` might be at some
// position less than `text.length`. it may also be _exactly_
// `text.length` if the `text` ends with a double `ch`, e.g.
// "\n\n", the `start` is set to `pos + 1` below, which is one
// after the first "\n" of the pair. it would also be split.
if (start <= text.length) {
const part = {
text: text.substr(start),
pos: start
};
pos = -1;
start = text.length + 1;
return part;
} else {
return null;
}
}
const end = pos - start;
const word = text.substr(start, end);
const part = {
text: word,
pos: start
};
start = pos + 1;
pos = text.indexOf(ch, start);
return part;
}
}
}
module.exports = Splitter;