Code-Qualität & Programmier-Snippets
Code Quality & Programming Snippets
Beispiele für sauberen, modularen & wartungsfreundlichen Code (TypeScript, React 19, C++20 & Gemini KI).
Examples of clean, modular & maintainable code (TypeScript, React 19, C++20 & Gemini AI).
// EcoChef Gemini AI Service (TypeScript) mit JSON-Schema Guard
export class GeminiService {
private apiKey: string;
constructor(apiKey: string) {
this.apiKey = apiKey;
}
async generateRecipe(ingredients: string[]): Promise<Recipe> {
const prompt = `Erstelle ein nachhaltiges Rezept mit: ${ingredients.join(', ')}. Antworte strikt in JSON.`;
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key=${this.apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ contents: [{ parts: [{ text: prompt }] }] })
});
const result = await response.json();
return this.validateRecipeSchema(result);
}
}
EcoChef Gemini API Integration (TypeScript): Kapselt den Aufruf an Google Gemini 1.5 Pro im modularen Service-Layer ab, erzwingt Schema-Validierung und berechnet Nährwerte & CO2-Einsparungen.
EcoChef Gemini API Integration (TypeScript): Encapsulates Google Gemini 1.5 Pro calls in a modular service layer with strict JSON schema validation and nutrition/carbon footprint analytics.
// Minecraft C++20 Voxel Engine: Redstone Propagation & Block Updates
struct BlockUpdate {
glm::ivec3 position;
uint8_t signalStrength;
};
void RedstoneSimulator::propagateSignal(glm::ivec3 source, uint8_t power) {
std::queue<BlockUpdate> updateQueue;
updateQueue.push({source, power});
while (!updateQueue.empty()) {
auto current = updateQueue.front();
updateQueue.pop();
if (current.signalStrength == 0) continue;
for (const auto& dir : ADJACENT_DIRECTIONS) {
glm::ivec3 target = current.position + dir;
if (world.getBlock(target).type == BlockType::RedstoneWire) {
uint8_t newPower = current.signalStrength - 1;
if (newPower > world.getSignal(target)) {
world.setSignal(target, newPower);
updateQueue.push({target, newPower});
}
}
}
}
}
Minecraft C++20 Voxel Simulation: Effiziente Breadth-First-Propagation für Redstone-Schaltungen in einer 3D-Voxel-Welt mit Zero-Allocation Chunks und OpenGL 4.5 Mesh-Rendering.
Minecraft C++20 Voxel Simulation: Efficient breadth-first signal propagation for Redstone circuits in a 3D voxel engine with zero-allocation chunks and OpenGL 4.5 mesh rendering.
// ElektroCheck AI: DGUV V3 PDF Report Parser mit OpenAI JSON-Guard
export async function analyzeInspectionPdf(pdfText: string): Promise<DguvReport> {
const response = await openai.chat.completions.create({
model: 'gpt-4o',
response_format: { type: 'json_object' },
messages: [
{
role: 'system',
content: 'Extrahiere Prüflinge, R_iso, R_pe, Grenzwerte und Mängel nach DGUV V3.'
},
{ role: 'user', content: pdfText }
]
});
const parsed = JSON.parse(response.choices[0].message.content);
return DguvReportSchema.parse(parsed); // Zod runtime validation
}
ElektroCheck AI DGUV-Analyse (Node.js & OpenAI): Strukturiert unstrukturierte Prüfprotokoll-PDFs in typsichere Datenobjekte mit Zod-Validierung und automatischer Mängelbewertung.
ElektroCheck AI DGUV Analytics (Node.js & OpenAI): Transforms unstructured electrical inspection PDFs into type-safe models using OpenAI JSON mode and Zod runtime schema validation.
import { useState, useEffect, useRef } from 'react';
export function useFetch(url, options = {}) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const cache = useRef({});
useEffect(() => {
if (!url) return;
if (cache.current[url]) {
setData(cache.current[url]);
setLoading(false);
return;
}
const controller = new AbortController();
setLoading(true);
fetch(url, { ...options, signal: controller.signal })
.then(res => {
if (!res.ok) throw new Error(`HTTP error: ${res.status}`);
return res.json();
})
.then(jsonData => {
cache.current[url] = jsonData;
setData(jsonData);
})
.catch(err => {
if (err.name !== 'AbortError') setError(err);
})
.finally(() => setLoading(false));
return () => controller.abort();
}, [url]);
return { data, loading, error };
}
React Custom Hook (`useFetch`): Implementiert autom. Caching zur Reduzierung von API-Calls, AbortController zur Vermeidung von Race Conditions bei unvollständigen Anfragen und sauberes Laden/Fehler-State-Management.
React Custom Hook (`useFetch`): Implements automatic client-side memory caching, AbortController request cancelation to prevent race conditions on component unmount, and structured loading/error state management.
// PWA Stale-While-Revalidate Caching mit Offline-Fallback
self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') return;
event.respondWith(
caches.open(CACHE_NAME).then(async (cache) => {
const cachedResponse = await cache.match(event.request);
const networkFetch = fetch(event.request)
.then((networkResponse) => {
if (networkResponse.ok) {
cache.put(event.request, networkResponse.clone());
}
return networkResponse;
})
.catch(() => cachedResponse || caches.match('offline.html'));
return cachedResponse || networkFetch;
})
);
});
PWA Cache-First mit Stale-While-Revalidate: Garantiert sofortige Ladezeiten auch ohne Internetverbindung und aktualisiert den lokalen Cache im Hintergrund für maximale Zuverlässigkeit.
PWA Cache-First with Stale-While-Revalidate: Delivers instant page loads even offline, silently refreshing cached assets in the background for maximum reliability.