From a1ea9429daae076bf0991c6a7b307f94d75175f0 Mon Sep 17 00:00:00 2001 From: Redm4x <2829180+Redm4x@users.noreply.github.com> Date: Tue, 2 Apr 2024 15:50:48 -0400 Subject: [PATCH] Add array helper --- api/src/utils/array/array.spec.ts | 19 +++++++++++++++++++ api/src/utils/array/array.ts | 7 +++++++ api/src/utils/map/provider.ts | 4 +++- 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 api/src/utils/array/array.spec.ts create mode 100644 api/src/utils/array/array.ts diff --git a/api/src/utils/array/array.spec.ts b/api/src/utils/array/array.spec.ts new file mode 100644 index 000000000..ff1263d2c --- /dev/null +++ b/api/src/utils/array/array.spec.ts @@ -0,0 +1,19 @@ +import { createFilterUnique } from "./array"; + +describe("array helpers", () => { + describe("createFilterUnique", () => { + it("should return a functionning unique filter with default equality matcher", () => { + const arrayWithDuplicate = [1, 2, 2, 3, 3, 3]; + const expected = [1, 2, 3]; + + expect(arrayWithDuplicate.filter(createFilterUnique())).toEqual(expected); + }); + + it("should return a functionning unique filter with custom matcher", () => { + const arrayWithDuplicate = [{ v: 1 }, { v: 2 }, { v: 2 }, { v: 3 }, { v: 3 }, { v: 3 }]; + const expected = [{ v: 1 }, { v: 2 }, { v: 3 }]; + + expect(arrayWithDuplicate.filter(createFilterUnique((a, b) => a.v === b.v))).toEqual(expected); + }); + }); +}); diff --git a/api/src/utils/array/array.ts b/api/src/utils/array/array.ts new file mode 100644 index 000000000..3a22c4800 --- /dev/null +++ b/api/src/utils/array/array.ts @@ -0,0 +1,7 @@ +type Matcher = (a: T, b: T) => boolean; + +export function createFilterUnique(matcher: Matcher = (a, b) => a === b): (value: T, index: number, array: T[]) => boolean { + return (value, index, array) => { + return array.findIndex((other) => matcher(value, other)) === index; + }; +} diff --git a/api/src/utils/map/provider.ts b/api/src/utils/map/provider.ts index 2eeee31b0..f8b91f24b 100644 --- a/api/src/utils/map/provider.ts +++ b/api/src/utils/map/provider.ts @@ -1,5 +1,6 @@ import { Provider, ProviderSnapshotNode } from "@shared/dbSchemas/akash"; import { Auditor, ProviderAttributesSchema, ProviderList } from "@src/types/provider"; +import { createFilterUnique } from "../array/array"; import semver from "semver"; export const mapProviderToList = ( @@ -93,8 +94,9 @@ export const mapProviderToList = ( function getDistinctGpuModelsFromNodes(nodes: ProviderSnapshotNode[]) { const gpuModels = nodes.flatMap((x) => x.gpus).map((x) => ({ vendor: x.vendor, model: x.name, ram: x.memorySize, interface: x.interface })); const distinctGpuModels = gpuModels.filter( - (x, i, arr) => arr.findIndex((o) => x.vendor === o.vendor && x.model === o.model && x.ram === o.ram && x.interface === o.interface) === i + createFilterUnique((a, b) => a.vendor === b.vendor && a.model === b.model && a.ram === b.ram && a.interface === b.interface) ); + return distinctGpuModels; }