w

Praktische Beispiele

Hier finden Sie eine Sammlung von praktischen Beispielen, die zeigen, wie das Text Diff Tool in verschiedenen Szenarien eingesetzt werden kann.

Code-Entwicklung

JavaScript-Funktion aktualisieren

Datei A (Original):

function calculateTotal(items) {
  let total = 0;
  for (let i = 0; i < items.length; i++) {
    total += items[i].price;
  }
  return total;
}

Datei B (Verbessert):

function calculateTotal(items) {
  if (!items || items.length === 0) {
    return 0;
  }

  return items.reduce((total, item) => {
    return total + (item.price || 0);
  }, 0);
}

Diff-Ergebnis:

+ 2   2 |     if (!items || items.length === 0) {
+ 3   3 |         return 0;
+ 4   4 |     }
+ 5   5 |
- 2   6 |     let total = 0;
- 3   7 |     for (let i = 0; i < items.length; i++) {
- 4   8 |         total += items[i].price;
- 5   9 |     }
- 6  10 |     return total;
+ 6   7 |     return items.reduce((total, item) => {
+ 7   8 |         return total + (item.price || 0);
+ 8   9 |     }, 0);

React-Komponente refactoring

Datei A (Klassenkomponente):

import React, { Component } from 'react';

class UserProfile extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user: null,
      loading: true,
    };
  }

  componentDidMount() {
    this.fetchUser();
  }

  fetchUser = async () => {
    try {
      const response = await fetch(`/api/users/${this.props.userId}`);
      const user = await response.json();
      this.setState({ user, loading: false });
    } catch (error) {
      console.error('Error fetching user:', error);
      this.setState({ loading: false });
    }
  };

  render() {
    const { user, loading } = this.state;

    if (loading) return <div>Loading...</div>;
    if (!user) return <div>User not found</div>;

    return (
      <div>
        <h1>{user.name}</h1>
        <p>{user.email}</p>
      </div>
    );
  }
}

Datei B (Funktionskomponente mit Hooks):

import React, { useState, useEffect } from 'react';

const UserProfile = ({ userId }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const response = await fetch(`/api/users/${userId}`);
        const userData = await response.json();
        setUser(userData);
      } catch (error) {
        console.error('Error fetching user:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchUser();
  }, [userId]);

  if (loading) return <div>Loading...</div>;
  if (!user) return <div>User not found</div>;

  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
    </div>
  );
};

Konfigurationsverwaltung

Docker Compose Konfiguration

Datei A (Entwicklung):

version: '3.8'
services:
  web:
    build: .
    ports:
      - '3000:3000'
    environment:
      - NODE_ENV=development
      - DATABASE_URL=postgresql://localhost:5432/myapp_dev
    volumes:
      - .:/app
      - /app/node_modules

  database:
    image: postgres:13
    environment:
      - POSTGRES_DB=myapp_dev
      - POSTGRES_USER=dev
      - POSTGRES_PASSWORD=dev123
    ports:
      - '5432:5432'

Datei B (Produktion):

version: '3.8'
services:
  web:
    build: .
    ports:
      - '80:3000'
    environment:
      - NODE_ENV=production
      - DATABASE_URL=${DATABASE_URL}
    restart: unless-stopped
    depends_on:
      - database

  database:
    image: postgres:13
    environment:
      - POSTGRES_DB=${POSTGRES_DB}
      - POSTGRES_USER=${POSTGRES_USER}
      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    restart: unless-stopped

volumes:
  postgres_data:

Package.json Dependencies

Datei A (Vor Update):

{
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "axios": "^0.21.1",
    "lodash": "^4.17.20"
  },
  "devDependencies": {
    "@types/react": "^17.0.0",
    "typescript": "^4.2.3",
    "webpack": "^5.24.0"
  }
}

Datei B (Nach Update):

{
  "dependencies": {
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "axios": "^1.3.0",
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "@types/react": "^18.0.0",
    "typescript": "^4.9.0",
    "webpack": "^5.75.0",
    "vite": "^4.0.0"
  }
}

API-Entwicklung

OpenAPI Spezifikation

Datei A (Version 1.0):

openapi: 3.0.0
info:
  title: User API
  version: 1.0.0
  description: API for user management

paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: List of users
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        email:
          type: string

Datei B (Version 2.0):

openapi: 3.0.0
info:
  title: User API
  version: 2.0.0
  description: Enhanced API for user management

paths:
  /users:
    get:
      summary: Get all users
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            default: 10
        - name: offset
          in: query
          schema:
            type: integer
            default: 0
      responses:
        '200':
          description: Paginated list of users
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserList'
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /users/{id}:
    get:
      summary: Get user by ID
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: User details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          description: User not found

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        email:
          type: string
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    UserList:
      type: object
      properties:
        users:
          type: array
          items:
            $ref: '#/components/schemas/User'
        total:
          type: integer
        limit:
          type: integer
        offset:
          type: integer
    Error:
      type: object
      properties:
        message:
          type: string
        code:
          type: string

Dokumentation

Markdown README

Datei A (Basis-Version):

# My Project

A simple web application built with React.

## Installation

```bash
npm install
```

Usage

npm start

Features

  • User authentication
  • Data visualization
  • Responsive design

**Datei B (Erweiterte Version):**
```markdown
# My Project

A modern web application built with React and TypeScript, featuring real-time data visualization and advanced user management.

## Table of Contents

- [Installation](#installation)
- [Usage](#usage)
- [Features](#features)
- [API Documentation](#api-documentation)
- [Contributing](#contributing)
- [License](#license)

## Installation

### Prerequisites

- Node.js 16.0 or higher
- npm 8.0 or higher

### Setup

```bash
# Clone the repository
git clone https://github.com/user/my-project.git
cd my-project

# Install dependencies
npm install

# Set up environment variables
cp .env.example .env

Usage

Development

npm run dev

Production

npm run build
npm start

Features

Core Features

  • User Authentication: Secure login with JWT tokens
  • Data Visualization: Interactive charts and graphs
  • Responsive Design: Mobile-first approach
  • Real-time Updates: WebSocket integration
  • API Integration: RESTful API with GraphQL support

Advanced Features

  • Dark Mode: Toggle between light and dark themes
  • Internationalization: Multi-language support
  • Accessibility: WCAG 2.1 AA compliant
  • Performance: Optimized bundle size and loading times

API Documentation

See API.md for detailed API documentation.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

MIT License - see LICENSE for details.


## Datenanalyse

### **JSON-Konfiguration**

**Datei A (Entwicklungskonfiguration):**
```json
{
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "myapp_dev",
    "username": "dev_user",
    "password": "dev_password"
  },
  "redis": {
    "host": "localhost",
    "port": 6379,
    "password": null
  },
  "logging": {
    "level": "debug",
    "file": "logs/app.log"
  },
  "features": {
    "enableAnalytics": false,
    "enableDebugMode": true,
    "enableExperimentalFeatures": true
  }
}

Datei B (Produktionskonfiguration):

{
  "database": {
    "host": "prod-db.example.com",
    "port": 5432,
    "name": "myapp_prod",
    "username": "prod_user",
    "password": "${DB_PASSWORD}",
    "ssl": true,
    "pool": {
      "min": 5,
      "max": 20
    }
  },
  "redis": {
    "host": "prod-redis.example.com",
    "port": 6379,
    "password": "${REDIS_PASSWORD}",
    "cluster": {
      "enabled": true,
      "nodes": ["redis-1.example.com:6379", "redis-2.example.com:6379", "redis-3.example.com:6379"]
    }
  },
  "logging": {
    "level": "info",
    "file": "/var/log/myapp/app.log",
    "maxSize": "100MB",
    "maxFiles": 5
  },
  "features": {
    "enableAnalytics": true,
    "enableDebugMode": false,
    "enableExperimentalFeatures": false
  },
  "monitoring": {
    "enabled": true,
    "endpoint": "https://monitoring.example.com",
    "apiKey": "${MONITORING_API_KEY}"
  }
}

Best Practices

Effektive Verwendung

  1. Regelmäßige Vergleiche: Vergleichen Sie Dateien regelmäßig, um Änderungen zu verfolgen
  2. Beschreibende Namen: Verwenden Sie aussagekräftige Namen für Ihre Dateien
  3. Verlauf nutzen: Speichern Sie wichtige Vergleiche im Verlauf
  4. Optionen anpassen: Experimentieren Sie mit verschiedenen Vergleichsoptionen

Performance-Tipps

  1. Dateigröße: Halten Sie Dateien unter 10.000 Zeilen für optimale Leistung
  2. Browser-Cache: Leeren Sie den Browser-Cache bei Problemen
  3. Moderne Browser: Verwenden Sie aktuelle Browser-Versionen

Sicherheitshinweise

  1. Sensitive Daten: Vermeiden Sie das Vergleichen von Passwörtern oder API-Schlüsseln
  2. Lokale Verarbeitung: Alle Verarbeitung erfolgt lokal in Ihrem Browser
  3. Verlauf bereinigen: Löschen Sie regelmäßig den Verlauf

Diese Beispiele zeigen die Vielseitigkeit und Leistungsfähigkeit des Text Diff Tools in verschiedenen Anwendungsszenarien.

War diese Seite hilfreich?