feat : merge mat
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { mergePosterMaterials } from "@/lib/material-poster";
|
||||
|
||||
describe("mergePosterMaterials", () => {
|
||||
it("combines amounts when leveling and talent materials use the same image", () => {
|
||||
expect(mergePosterMaterials([
|
||||
{ key: "talent", amount: 9, name: "Talent", imageUrl: "/shared.webp" },
|
||||
{ key: "leveling", amount: 18, name: "Leveling", imageUrl: "/shared.webp" },
|
||||
])).toEqual([
|
||||
{ key: "talent", amount: 27, name: "Talent", imageUrl: "/shared.webp" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps materials without images separate", () => {
|
||||
const materials = [
|
||||
{ key: "first", amount: 1, name: "First", imageUrl: null },
|
||||
{ key: "second", amount: 2, name: "Second", imageUrl: null },
|
||||
];
|
||||
|
||||
expect(mergePosterMaterials(materials)).toEqual(materials);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
export type PosterMaterial = {
|
||||
key: string;
|
||||
amount: number;
|
||||
name: string;
|
||||
imageUrl: string | null;
|
||||
};
|
||||
|
||||
export function mergePosterMaterials(materials: PosterMaterial[]): PosterMaterial[] {
|
||||
const merged: PosterMaterial[] = [];
|
||||
const indexByImageUrl = new Map<string, number>();
|
||||
|
||||
for (const material of materials) {
|
||||
if (!material.imageUrl) {
|
||||
merged.push(material);
|
||||
continue;
|
||||
}
|
||||
|
||||
const existingIndex = indexByImageUrl.get(material.imageUrl);
|
||||
if (existingIndex === undefined) {
|
||||
indexByImageUrl.set(material.imageUrl, merged.length);
|
||||
merged.push(material);
|
||||
continue;
|
||||
}
|
||||
|
||||
const existing = merged[existingIndex];
|
||||
merged[existingIndex] = {
|
||||
...existing,
|
||||
amount: existing.amount + material.amount,
|
||||
};
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
Reference in New Issue
Block a user