Add comprehensive skills and documentation for various technologies

This commit is contained in:
duthaho
2025-11-29 18:07:28 +07:00
commit ef96f165ef
60 changed files with 10538 additions and 0 deletions
@@ -0,0 +1,101 @@
# JavaScript
## Description
Modern JavaScript (ES6+) patterns and best practices for Node.js and browser environments.
## When to Use
- Working with JavaScript files (.js, .mjs)
- Browser scripting
- Node.js applications without TypeScript
---
## Core Patterns
### Modern Syntax
```javascript
// Destructuring
const { name, email } = user;
const [first, ...rest] = items;
// Spread operator
const merged = { ...defaults, ...options };
const combined = [...array1, ...array2];
// Template literals
const message = `Hello, ${name}!`;
// Optional chaining and nullish coalescing
const city = user?.address?.city ?? 'Unknown';
```
### Async Patterns
```javascript
// Async/await
async function fetchData(url) {
const response = await fetch(url);
if (!response.ok) throw new Error('Fetch failed');
return response.json();
}
// Promise.all for parallel
const results = await Promise.all([
fetchData(url1),
fetchData(url2),
]);
// Error handling
try {
const data = await fetchData(url);
} catch (error) {
console.error('Failed:', error.message);
}
```
### Array Methods
```javascript
// Map, filter, reduce
const names = users.map(u => u.name);
const active = users.filter(u => u.active);
const total = items.reduce((sum, i) => sum + i.price, 0);
// Find and includes
const user = users.find(u => u.id === id);
const hasAdmin = users.some(u => u.role === 'admin');
```
### Classes
```javascript
class UserService {
#db; // Private field
constructor(database) {
this.#db = database;
}
async findById(id) {
return this.#db.users.find(u => u.id === id);
}
}
```
## Best Practices
1. Use `const` by default, `let` when needed
2. Avoid `var` - use block-scoped declarations
3. Use arrow functions for callbacks
4. Handle all promise rejections
5. Use ESLint for consistent style
## Common Pitfalls
- **Implicit type coercion**: Use `===` instead of `==`
- **Callback hell**: Use async/await
- **Mutating objects**: Create new objects with spread
- **Not handling errors**: Always catch promise rejections
+110
View File
@@ -0,0 +1,110 @@
# Python
## Description
Python development expertise including type hints, async patterns, virtual environments, and Pythonic idioms.
## When to Use
- Working with Python files (.py)
- Writing Python scripts or applications
- Using Python frameworks (Django, FastAPI, Flask)
- Data processing and automation
---
## Core Patterns
### Type Hints
```python
from typing import Optional, List, Dict, Union
from collections.abc import Callable
def process_items(
items: List[str],
callback: Callable[[str], None],
config: Optional[Dict[str, Any]] = None
) -> List[str]:
"""Process items with optional callback."""
return [callback(item) for item in items]
```
### Async/Await
```python
import asyncio
from typing import List
async def fetch_data(url: str) -> dict:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()
async def fetch_all(urls: List[str]) -> List[dict]:
return await asyncio.gather(*[fetch_data(url) for url in urls])
```
### Context Managers
```python
from contextlib import contextmanager
@contextmanager
def managed_resource():
resource = acquire_resource()
try:
yield resource
finally:
release_resource(resource)
# Usage
with managed_resource() as r:
r.do_something()
```
### Dataclasses
```python
from dataclasses import dataclass, field
from datetime import datetime
@dataclass
class User:
id: int
email: str
name: str
created_at: datetime = field(default_factory=datetime.now)
def __post_init__(self):
self.email = self.email.lower()
```
### Pydantic Models
```python
from pydantic import BaseModel, EmailStr, Field
class UserCreate(BaseModel):
email: EmailStr
name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=8)
class Config:
str_strip_whitespace = True
```
## Best Practices
1. Use type hints for all public functions
2. Use dataclasses or Pydantic for data models
3. Prefer context managers for resource management
4. Use async for I/O-bound operations
5. Follow PEP 8 style guidelines
## Common Pitfalls
- **Mutable default arguments**: Use `None` and initialize in function
- **Not closing resources**: Use `with` statements
- **Blocking in async**: Use `asyncio.to_thread()` for CPU work
- **Catching bare exceptions**: Be specific with exception types
@@ -0,0 +1,128 @@
# TypeScript
## Description
TypeScript development with strict typing, advanced type utilities, and modern patterns.
## When to Use
- Working with TypeScript files (.ts, .tsx)
- Building typed JavaScript applications
- React/Next.js development
- Node.js backend development
---
## Core Patterns
### Type Definitions
```typescript
// Interfaces for objects
interface User {
id: string;
email: string;
name: string;
createdAt: Date;
}
// Types for unions and utilities
type Status = 'pending' | 'active' | 'inactive';
type UserWithStatus = User & { status: Status };
// Generic types
type ApiResponse<T> = {
data: T;
error?: string;
status: number;
};
```
### Utility Types
```typescript
// Partial - all properties optional
type UserUpdate = Partial<User>;
// Pick - select properties
type UserPreview = Pick<User, 'id' | 'name'>;
// Omit - exclude properties
type UserWithoutId = Omit<User, 'id'>;
// Record - dictionary type
type UserMap = Record<string, User>;
```
### Async Patterns
```typescript
async function fetchUser(id: string): Promise<User> {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`Failed to fetch user: ${response.status}`);
}
return response.json();
}
// Error handling
async function safeOperation<T>(
operation: () => Promise<T>
): Promise<[T, null] | [null, Error]> {
try {
const result = await operation();
return [result, null];
} catch (error) {
return [null, error as Error];
}
}
```
### Class Patterns
```typescript
class UserService {
constructor(private readonly db: Database) {}
async findById(id: string): Promise<User | null> {
return this.db.users.findUnique({ where: { id } });
}
async create(data: UserCreate): Promise<User> {
return this.db.users.create({ data });
}
}
```
### Zod Validation
```typescript
import { z } from 'zod';
const UserSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
password: z.string().min(8),
});
type UserInput = z.infer<typeof UserSchema>;
function validateUser(data: unknown): UserInput {
return UserSchema.parse(data);
}
```
## Best Practices
1. Enable strict mode in tsconfig.json
2. Avoid `any` - use `unknown` and type guards
3. Use interfaces for object shapes, types for unions
4. Prefer `const` assertions for literal types
5. Use discriminated unions for state
## Common Pitfalls
- **Using `any`**: Defeats type safety
- **Not handling null/undefined**: Use strict null checks
- **Type assertions**: Prefer type guards
- **Ignoring errors**: Handle all promise rejections