recipes.helper.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import type { FluidProductPrototype, ItemProductPrototype, RecipePrototype } from "../factorio-dump.models.ts";
  2. import type { Item } from "../factorio-process-data.models.ts";
  3. export type Ingredient = {
  4. type: "fluid" | "item";
  5. itemId: string;
  6. amount: number;
  7. };
  8. export type Recipe = {
  9. name: string;
  10. icon?: string;
  11. subgroup: string;
  12. order?: string;
  13. category?: string;
  14. additional_categories?: string[];
  15. allow_productivity?: boolean;
  16. allow_quality?: boolean;
  17. allow_speed?: boolean;
  18. ingredients?: Ingredient[];
  19. results?: Array<ItemProductPrototype | FluidProductPrototype>;
  20. };
  21. export function getRecipeIcon(recipe: RecipePrototype, mainProduct: Item | undefined): string {
  22. if (recipe.icons || recipe.icon) return `recipe/${recipe.name}.png`;
  23. if (mainProduct && mainProduct.icon) return mainProduct.icon;
  24. console.warn(`No icon found for :${recipe.name}`);
  25. return "";
  26. }
  27. export function getRecipeSubGroup(recipe: RecipePrototype, mainProduct: Item | undefined): string {
  28. if (recipe.subgroup) return recipe.subgroup;
  29. if (mainProduct) return mainProduct.subgroup;
  30. return "other";
  31. }
  32. export function getMainProductName(recipe: RecipePrototype): string {
  33. if (recipe.results?.length == 1) {
  34. return recipe.results[0].name;
  35. } else if (recipe.results && recipe.main_product) {
  36. const mainProduct = recipe.main_product;
  37. const result = recipe.results.find((r) => r.name === mainProduct);
  38. if (result) {
  39. return result.name;
  40. }
  41. throw new Error(`Main product '${mainProduct}' declared by recipe '${recipe.name}' not found in results`);
  42. }
  43. return "";
  44. }
  45. export function parseRecipe(recipe: RecipePrototype, itemsMap: Record<string, Item>): Recipe {
  46. const rawIngredient = Array.isArray(recipe.ingredients) ? recipe.ingredients : [];
  47. const ingredients = rawIngredient.map((i) => ({ itemId: i.name, amount: i.amount, type: i.type }));
  48. const mainProduct = itemsMap[getMainProductName(recipe)];
  49. const r: Recipe = {
  50. name: recipe.name,
  51. icon: getRecipeIcon(recipe, mainProduct),
  52. subgroup: getRecipeSubGroup(recipe, mainProduct),
  53. order: recipe.order,
  54. category: recipe.category,
  55. additional_categories: recipe.additional_categories,
  56. ingredients,
  57. results: recipe.results,
  58. };
  59. if (recipe.category) r.category = recipe.category;
  60. if (recipe.additional_categories) r.additional_categories = recipe.additional_categories;
  61. if (recipe.allow_productivity) r.allow_productivity = true;
  62. if (recipe.allow_quality) r.allow_quality = true;
  63. if (recipe.allow_speed) r.allow_speed = true;
  64. return r;
  65. }