From 8482a412afd06a5a67ec8e3d664ab3cb6cdf6b11 Mon Sep 17 00:00:00 2001 From: Daniel Cassidy Date: Mon, 17 Jan 2022 14:17:35 +0000 Subject: [PATCH] feat(prefixmatch): add prefixMatch function --- index.test.ts | 9 +++++++++ index.ts | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+) 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 3f2af280..f0bd5f16 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; }