Skip to content

Commit

Permalink
Add array helper
Browse files Browse the repository at this point in the history
  • Loading branch information
Redm4x committed Apr 2, 2024
1 parent 72040a3 commit a1ea942
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
19 changes: 19 additions & 0 deletions api/src/utils/array/array.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
});
7 changes: 7 additions & 0 deletions api/src/utils/array/array.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
type Matcher<T> = (a: T, b: T) => boolean;

export function createFilterUnique<T>(matcher: Matcher<T> = (a, b) => a === b): (value: T, index: number, array: T[]) => boolean {
return (value, index, array) => {
return array.findIndex((other) => matcher(value, other)) === index;
};
}
4 changes: 3 additions & 1 deletion api/src/utils/map/provider.ts
Original file line number Diff line number Diff line change
@@ -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 = (
Expand Down Expand Up @@ -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;
}

Expand Down

0 comments on commit a1ea942

Please sign in to comment.