Skip to content

Commit 85816ed

Browse files
authored
Merge pull request #31 from scramjetorg/feature/stringstream-split-regex
Support regexp in 'StringStream.split' method
2 parents f74bb8b + a40cd19 commit 85816ed

File tree

3 files changed

+25
-7
lines changed

3 files changed

+25
-7
lines changed

package.json

+4-4
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,10 @@
5454
]
5555
},
5656
"nyc": {
57-
"branches": 70,
58-
"lines": 70,
59-
"functions": 70,
60-
"statements": 70,
57+
"branches": 75,
58+
"lines": 90,
59+
"functions": 90,
60+
"statements": 85,
6161
"include": "build/src/",
6262
"exclude": "build/test/**/*.js"
6363
},

src/streams/string-stream.ts

+7-3
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ export class StringStream extends DataStream<string> {
77
return new StringStream();
88
}
99

10-
split(splitBy: string) {
10+
split(splitBy: string): StringStream;
11+
split(splitBy: RegExp): StringStream;
12+
split(splitBy: string | RegExp): StringStream {
1113
const splitter = this.getSplitter(splitBy);
1214
const onEndYield = () => ({ yield: splitter.emitLastValue, value: splitter.lastValue });
1315

@@ -28,18 +30,20 @@ export class StringStream extends DataStream<string> {
2830
return super.flatMap(callback, ...args) as StringStream;
2931
}
3032

31-
private getSplitter(splitBy: string) {
33+
private getSplitter(splitBy: string | RegExp) {
3234
const result: any = {
3335
emitLastValue: false,
3436
lastValue: ""
3537
};
38+
const testFn = toString.call(splitBy) === "[object RegExp]"
39+
? (chunk: string) => (splitBy as RegExp).test(chunk) : (chunk: string) => chunk.includes(splitBy as string);
3640

3741
result.fn = (chunk: string): string[] => {
3842
const tmpChunk = `${result.lastValue}${chunk}`;
3943

4044
result.emitLastValue = true;
4145

42-
if (!tmpChunk.includes(splitBy)) {
46+
if (!testFn(tmpChunk)) {
4347
result.lastValue = tmpChunk;
4448
return [];
4549
}

test/unit/streams/string/split.spec.ts

+14
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,17 @@ test("StringStream split can stream with only one split value", async (t) => {
6464

6565
t.deepEqual(result, ["", ""]);
6666
});
67+
68+
test("StringStream can split chunks by given regexp #1", async (t) => {
69+
const stringStream = StringStream.from(["foo1bar", "baz111bax", "123", "345", "011", "201"]);
70+
const result = await stringStream.split(/1+/).toArray();
71+
72+
t.deepEqual(result, ["foo", "barbaz", "bax", "233450", "20", ""]);
73+
});
74+
75+
test("StringStream can split chunks by given regexp #2", async (t) => {
76+
const stringStream = StringStream.from(["foo1bar", "baz111bax", "123", "345", "011", "201"]);
77+
const result = await stringStream.split(/1{1,2}/).toArray();
78+
79+
t.deepEqual(result, ["foo", "barbaz", "", "bax", "233450", "20", ""]);
80+
});

0 commit comments

Comments
 (0)