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

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

authored by kitten.sh and committed by GitHub acbba9ac 26e15cfe

Changed files
+29 -1
.changeset
src
+5
.changeset/rich-pans-smoke.md
··· 1 + --- 2 + 'wonka': minor 3 + --- 4 + 5 + Add `addOne` argument to `takeWhile`, allowing an additional value to be issued.
+18
src/__tests__/operators.test.ts
··· 772 772 operators.takeWhile((x: any) => x < 2)(source)(fn); 773 773 next(1); 774 774 next(2); 775 + next(3); 775 776 776 777 expect(fn.mock.calls).toEqual([[start(expect.any(Function))], [push(1)], [SignalKind.End]]); 778 + }); 779 + 780 + it('emits values while a predicate passes for all values plus an additional one', () => { 781 + const { source, next } = sources.makeSubject<number>(); 782 + const fn = vi.fn(); 783 + 784 + operators.takeWhile((x: any) => x < 2, true)(source)(fn); 785 + next(1); 786 + next(2); 787 + next(3); 788 + 789 + expect(fn.mock.calls).toEqual([ 790 + [start(expect.any(Function))], 791 + [push(1)], 792 + [push(2)], 793 + [SignalKind.End], 794 + ]); 777 795 }); 778 796 }); 779 797
+6 -1
src/operators.ts
··· 1254 1254 /** Takes values from an input Source until a predicate function returns `false`. 1255 1255 * 1256 1256 * @param predicate - A function returning a boolean per value. 1257 + * @param addOne - Lets an additional input value pass on. 1257 1258 * @returns An {@link Operator}. 1258 1259 * 1259 1260 * @remarks 1260 1261 * `takeWhile` will issue all values as normal from the input {@link Source} until the `predicate` 1261 1262 * function returns `false`. When the `predicate` function returns `false`, the current value is 1262 1263 * omitted and the {@link Source} is closed. 1264 + * 1265 + * If `addOne` is set to `true`, the value for which the `predicate` first returned `false` is 1266 + * issued and passed on as well instead of being omitted. 1263 1267 * 1264 1268 * @example 1265 1269 * ```ts ··· 1272 1276 * ); 1273 1277 * ``` 1274 1278 */ 1275 - export function takeWhile<T>(predicate: (value: T) => boolean): Operator<T, T> { 1279 + export function takeWhile<T>(predicate: (value: T) => boolean, addOne?: boolean): Operator<T, T> { 1276 1280 return source => sink => { 1277 1281 let talkback = talkbackPlaceholder; 1278 1282 let ended = false; ··· 1287 1291 sink(signal); 1288 1292 } else if (!predicate(signal[0])) { 1289 1293 ended = true; 1294 + if (addOne) sink(signal); 1290 1295 sink(SignalKind.End); 1291 1296 talkback(TalkbackKind.Close); 1292 1297 } else {