Skip to content

Commit

Permalink
feat(stream): add ifEmpty option to Stream.join
Browse files Browse the repository at this point in the history
  • Loading branch information
vitoke committed Dec 22, 2021
1 parent 704297a commit 53d520a
Show file tree
Hide file tree
Showing 9 changed files with 460 additions and 162 deletions.
298 changes: 219 additions & 79 deletions deno_dist/list/interface.ts

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion deno_dist/stream/stream/constructors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ class EmptyStream<T = any> extends StreamBase<T> implements Stream<T> {
intersperse(): Stream<T> {
return this;
}
join({ start = '', end = '' } = {}): string {
join({ start = '', end = '', ifEmpty = undefined } = {}): string {
if (undefined !== ifEmpty) return ifEmpty;
return start.concat(end);
}
mkGroup({
Expand Down
2 changes: 2 additions & 0 deletions deno_dist/stream/stream/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,7 @@ export interface Stream<T> extends FastIterable<T>, Streamable<T> {
* * start: (optional) a start string to prepend at the start
* * end: (optional) an end string to append at the end
* * valueToString: (default: String) a function converting a Stream element to a string
* * ifEmpty: (optional) a string to return instead of the start and end tag if the stream is empty
* @example
* Stream.of(1, 2, 3).join({ start: '<', sep: ', ', end: '>' })
* // => '<1, 2, 3>'
Expand All @@ -519,6 +520,7 @@ export interface Stream<T> extends FastIterable<T>, Streamable<T> {
start?: string;
end?: string;
valueToString?: (value: T) => string;
ifEmpty?: string;
}): string;
/**
* Returns a Stream starting with `options.sep`, then returning the elements of this Stream interspersed with `options.sep`, and ending with
Expand Down
6 changes: 5 additions & 1 deletion deno_dist/stream/stream/stream-custom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -400,12 +400,16 @@ export abstract class StreamBase<T> implements Stream<T> {
start = '',
end = '',
valueToString = String,
ifEmpty = undefined,
} = {}): string {
const done = Symbol('Done');
const iterator = this[Symbol.iterator]();
let value: T | typeof done = iterator.fastNext(done);

if (done === value) return start.concat(end);
if (done === value) {
if (undefined !== ifEmpty) return ifEmpty;
return start.concat(end);
}

let result = start.concat(valueToString(value));

Expand Down

0 comments on commit 53d520a

Please sign in to comment.