Mirror: 🎩 A tiny but capable push & pull stream library for TypeScript and Flow

feat: Add an addOne argument to takeWhile (#156)

Changed files
+29 -1
.changeset
src
+5
.changeset/rich-pans-smoke.md
···
+
---
+
'wonka': minor
+
---
+
+
Add `addOne` argument to `takeWhile`, allowing an additional value to be issued.
+18
src/__tests__/operators.test.ts
···
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],
+
]);
});
});
+6 -1
src/operators.ts
···
/** 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
···
* );
* ```
*/
-
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;
···
sink(signal);
} else if (!predicate(signal[0])) {
ended = true;
+
if (addOne) sink(signal);
sink(SignalKind.End);
talkback(TalkbackKind.Close);
} else {