1
+ /**
2
+ * Asynchronous generator that yields characters from the input stream until it encounters
3
+ * an end-of-line character followed by a non-whitespace character.
4
+ *
5
+ * @param {AsyncGenerator<string> } stream - The input stream of characters.
6
+ * @param {string[] } endOfLine - An array of characters considered as end-of-line markers.
7
+ * @param {() => void } fullStop - A function to be called when the generator stops.
8
+ * @yields {string} Characters from the input stream.
9
+ * @returns {AsyncGenerator<string> } An async generator that yields characters.
10
+ */
1
11
export async function * onlyWhitespaceAfterEndOfLine (
2
12
stream : AsyncGenerator < string > ,
3
13
endOfLine : string [ ] ,
4
14
fullStop : ( ) => void ,
5
15
) : AsyncGenerator < string > {
6
16
let pending = "" ;
17
+
7
18
for await ( let chunk of stream ) {
8
19
chunk = pending + chunk ;
9
20
pending = "" ;
21
+
10
22
for ( let i = 0 ; i < chunk . length - 1 ; i ++ ) {
11
23
if (
12
24
endOfLine . includes ( chunk [ i ] ) &&
@@ -17,6 +29,7 @@ export async function* onlyWhitespaceAfterEndOfLine(
17
29
return ;
18
30
}
19
31
}
32
+
20
33
if ( endOfLine . includes ( chunk [ chunk . length - 1 ] ) ) {
21
34
pending = chunk [ chunk . length - 1 ] ;
22
35
yield chunk . slice ( 0 , chunk . length - 1 ) ;
@@ -27,6 +40,11 @@ export async function* onlyWhitespaceAfterEndOfLine(
27
40
yield pending ;
28
41
}
29
42
43
+ /**
44
+ * Yields characters from the stream, stopping if the first character is a newline.
45
+ * @param {AsyncGenerator<string> } stream - The input character stream.
46
+ * @yields {string} Characters from the stream.
47
+ */
30
48
export async function * noFirstCharNewline ( stream : AsyncGenerator < string > ) {
31
49
let first = true ;
32
50
for await ( const char of stream ) {
@@ -40,6 +58,20 @@ export async function* noFirstCharNewline(stream: AsyncGenerator<string>) {
40
58
}
41
59
}
42
60
61
+ /**
62
+ * Asynchronously yields characters from the input stream, stopping if a stop token is encountered.
63
+ *
64
+ * @param {AsyncGenerator<string> } stream - The input stream of characters.
65
+ * @param {string[] } stopTokens - Array of tokens that signal when to stop yielding.
66
+ * @yields {string} Characters from the input stream.
67
+ * @returns {AsyncGenerator<string> } An async generator that yields characters until a stop condition is met.
68
+ * @description
69
+ * 1. If no stop tokens are provided, yields all characters from the stream.
70
+ * 2. Otherwise, buffers incoming chunks and checks for stop tokens.
71
+ * 3. Yields characters one by one if no stop token is found at the start of the buffer.
72
+ * 4. Stops yielding and returns if a stop token is encountered.
73
+ * 5. After the stream ends, yields any remaining buffered characters.
74
+ */
43
75
export async function * stopAtStopTokens (
44
76
stream : AsyncGenerator < string > ,
45
77
stopTokens : string [ ] ,
0 commit comments