Skip to content

Commit

Permalink
feat: add toString
Browse files Browse the repository at this point in the history
Add toString(separator) method for Sequence
  • Loading branch information
Tomi Turtiainen authored and tomi committed Mar 6, 2021
1 parent 4023ab8 commit e744b10
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/Sequence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,12 @@ export class SequenceImpl<TItem> implements Iterable<TItem>, Sequence<TItem> {
return new Set(this._iterable);
}

toString(separator: string = ","): string {
return Array.isArray(this._iterable)
? this._iterable.join(separator)
: copyIntoAnArray(this._iterable).join(separator);
}

private _sequenceFromGenerator<TResult = TItem>(
factoryFn: Function,
restArgs?: any[]
Expand Down
15 changes: 15 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,21 @@ export interface Sequence<TItem> extends Iterable<TItem> {
* ```
*/
toSet(): Set<TItem>;
/**
* Converts the sequence to a string using the given separator
*
* @param separator A string used to separate one element of a sequence from the next in the resulting String. If omitted, the elements are separated with a comma.
*
* @example
* ```typescript
* // Returns a string "1,2,3"
* from([1, 2, 3]).toString();
*
* // Returns a string "1 - 2 - 3"
* from([1, 2, 3]).toString(" - ");
* ```
*/
toString(separator?: string): string;
}

/**
Expand Down
25 changes: 25 additions & 0 deletions test/fromfrom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1347,4 +1347,29 @@ describe("fromfrom", () => {
expect(from([1, 2]).toSet()).toEqual(new Set([1, 2]));
});
});

describe("toString", () => {
it("returns a string", () => {
expect(from([1, 2]).toString(",")).toEqual("1,2");
});

it("uses comma as a default separator", () => {
expect(from([1, 2]).toString()).toEqual("1,2");
});

it("can be given a custom separator", () => {
expect(from([1, 2]).toString("_")).toEqual("1_2");
});

it("works with generator input", () => {
function* generate() {
let i = 1;
while (i < 3) {
yield i;
i++;
}
}
expect(from(generate()).toString("_")).toEqual("1_2");
});
});
});

0 comments on commit e744b10

Please sign in to comment.