Skip to content

Commit e155f67

Browse files
committed
Support regexp in 'StringStream.split' method
1 parent f74bb8b commit e155f67

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

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)