Skip to content

Commit

Permalink
feat: Add an addOne argument to takeWhile (#156)
Browse files Browse the repository at this point in the history
  • Loading branch information
kitten authored Mar 27, 2023
1 parent 26e15cf commit acbba9a
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/rich-pans-smoke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'wonka': minor
---

Add `addOne` argument to `takeWhile`, allowing an additional value to be issued.
18 changes: 18 additions & 0 deletions src/__tests__/operators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -772,9 +772,27 @@ describe('takeWhile', () => {
operators.takeWhile((x: any) => x < 2)(source)(fn);
next(1);
next(2);
next(3);

expect(fn.mock.calls).toEqual([[start(expect.any(Function))], [push(1)], [SignalKind.End]]);
});

it('emits values while a predicate passes for all values plus an additional one', () => {
const { source, next } = sources.makeSubject<number>();
const fn = vi.fn();

operators.takeWhile((x: any) => x < 2, true)(source)(fn);
next(1);
next(2);
next(3);

expect(fn.mock.calls).toEqual([
[start(expect.any(Function))],
[push(1)],
[push(2)],
[SignalKind.End],
]);
});
});

describe('takeLast', () => {
Expand Down
7 changes: 6 additions & 1 deletion src/operators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1254,13 +1254,17 @@ export function takeUntil<S, T>(notifier: Source<S>): Operator<T, T> {
/** Takes values from an input Source until a predicate function returns `false`.
*
* @param predicate - A function returning a boolean per value.
* @param addOne - Lets an additional input value pass on.
* @returns An {@link Operator}.
*
* @remarks
* `takeWhile` will issue all values as normal from the input {@link Source} until the `predicate`
* function returns `false`. When the `predicate` function returns `false`, the current value is
* omitted and the {@link Source} is closed.
*
* If `addOne` is set to `true`, the value for which the `predicate` first returned `false` is
* issued and passed on as well instead of being omitted.
*
* @example
* ```ts
* pipe(
Expand All @@ -1272,7 +1276,7 @@ export function takeUntil<S, T>(notifier: Source<S>): Operator<T, T> {
* );
* ```
*/
export function takeWhile<T>(predicate: (value: T) => boolean): Operator<T, T> {
export function takeWhile<T>(predicate: (value: T) => boolean, addOne?: boolean): Operator<T, T> {
return source => sink => {
let talkback = talkbackPlaceholder;
let ended = false;
Expand All @@ -1287,6 +1291,7 @@ export function takeWhile<T>(predicate: (value: T) => boolean): Operator<T, T> {
sink(signal);
} else if (!predicate(signal[0])) {
ended = true;
if (addOne) sink(signal);
sink(SignalKind.End);
talkback(TalkbackKind.Close);
} else {
Expand Down

0 comments on commit acbba9a

Please sign in to comment.