diff --git a/index.test.ts b/index.test.ts index 6d2da170..da36b848 100644 --- a/index.test.ts +++ b/index.test.ts @@ -39,6 +39,7 @@ import { or, partition, partitionWhile, + prefixMatch, prepend, product, remove, @@ -169,6 +170,14 @@ test("equal", t => { ); }); +test("prefixMatch", t => { + t.true(prefixMatch([], [])); + t.true(prefixMatch([1, 2, 3], [])); + t.true(prefixMatch([1, 2, 3, 4], [1, 2])); + t.false(prefixMatch([1, 3, 4], [1, 2])); + t.false(prefixMatch([], [1])); +}); + test("map", t => { t.deepEqual( map([1, 2, 3], e => e + 1), diff --git a/index.ts b/index.ts index c02cede5..40f918de 100644 --- a/index.ts +++ b/index.ts @@ -254,6 +254,31 @@ export function notEqualFn( return a => notEqual(a, b, elementsEqual); } +export function prefixMatch( + a: ArrayLike, + b: ArrayLike, + elementsEqual: (a: T, b: T) => boolean = defaultEqual +): boolean { + if (a.length < b.length) { + return false; + } + + for (let i = 0; i < b.length; ++i) { + if (a[i] !== b[i]) { + return false; + } + } + + return true; +} + +export function prefixMatchFn( + b: ArrayLike, + elementsEqual: (a: T, b: T) => boolean = defaultEqual +): (a: ArrayLike) => boolean { + return a => prefixMatch(a, b, elementsEqual); +} + function defaultEqual(a: unknown, b: unknown): boolean { return a === b; }