Skip to content

Commit 654ed21

Browse files
committed
feat(prefixMatch): add prefixMatch function
1 parent 881e8bf commit 654ed21

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

index.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
last,
1010
notEmpty,
1111
only,
12+
prefixMatch,
1213
push,
1314
tail,
1415
take,
@@ -135,3 +136,11 @@ test("equal", async t => {
135136
)
136137
);
137138
});
139+
140+
test("prefixMatch", async t => {
141+
t.true(await prefixMatch(asyncIterable([]), []));
142+
t.true(await prefixMatch(asyncIterable([1, 2, 3]), []));
143+
t.true(await prefixMatch(asyncIterable([1, 2, 3, 4]), [1, 2]));
144+
t.false(await prefixMatch(asyncIterable([1, 3, 4]), [1, 2]));
145+
t.false(await prefixMatch(asyncIterable([]), [1]));
146+
});

index.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,3 +348,37 @@ export function notEqualFn<T>(
348348
}
349349

350350
export const asyncNotEqualFn = notEqualFn;
351+
352+
export async function prefixMatch<T>(
353+
a: AsyncIterableLike<T>,
354+
b: AsyncIterableLike<T>,
355+
elementsEqual: (a: T, b: T) => boolean | Promise<boolean> = defaultEqual
356+
): Promise<boolean> {
357+
const ait = asyncIterator(a);
358+
const bit = asyncIterator(b);
359+
360+
let ar = await ait.next();
361+
let br = await bit.next();
362+
363+
while (ar.done !== true && br.done !== true) {
364+
if (!(await elementsEqual(ar.value, br.value))) {
365+
return false;
366+
}
367+
368+
ar = await ait.next();
369+
br = await bit.next();
370+
}
371+
372+
return br.done ?? false;
373+
}
374+
375+
export const asyncPrefixMatch = prefixMatch;
376+
377+
export function prefixMatchFn<T>(
378+
b: AsyncIterableLike<T>,
379+
elementsEqual: (a: T, b: T) => boolean | Promise<boolean> = defaultEqual
380+
): (a: AsyncIterableLike<T>) => Promise<boolean> {
381+
return async a => prefixMatch(a, b, elementsEqual);
382+
}
383+
384+
export const asyncPrefixMatchFn = prefixMatchFn;

0 commit comments

Comments
 (0)