Advanced Usage Examples
Explore advanced features of ExplainThis with these comprehensive examples. Learn how to use batch processing, context-aware analysis, and specialized modes.
Batch Processing
Process multiple code snippets in a single request
Code to Analyze
Source Code
interface User {
id: string;
name: string;
email: string;
role: 'admin' | 'user';
}
const processUsers = async (users: User[]) => {
const results = await Promise.all(
users.map(async user => {
try {
await validateUser(user);
await updateUserRole(user);
return { success: true, user };
} catch (error) {
return { success: false, error, user };
}
})
);
return {
successful: results.filter(r => r.success),
failed: results.filter(r => !r.success),
};
};Advanced API Usage
SDK Usage
import { ExplainThis } from '@explainthis/sdk';
const explainThis = new ExplainThis(process.env.EXPLAINTHIS_API_KEY);
// Prepare multiple code snippets
const snippets = [
{ code: validateUser.toString(), context: 'User validation' },
{ code: updateUserRole.toString(), context: 'Role update' },
{ code: processUsers.toString(), context: 'Main process' },
];
// Get batch explanations
const explanations = await explainThis.batchExplain({
snippets,
mode: 'performance',
language: 'typescript',
});
// Process each explanation
explanations.forEach((exp, i) => {
console.log(`Explanation for ${snippets[i].context}:`);
console.log(exp);
});Analysis Details
This advanced example demonstrates batch processing of user data with TypeScript. It uses Promise.all for concurrent processing, includes error handling for each user, and returns structured results separating successful and failed operations. The explanation request processes multiple related functions in a single batch for better context.
Custom Analysis with Context
Analyze code with additional context and custom settings
Code to Analyze
Source Code
from typing import List, Dict, Optional
from datetime import datetime
import pandas as pd
class DataAnalyzer:
def __init__(self, config: Dict[str, any]):
self.config = config
self.cache: Dict[str, pd.DataFrame] = {}
def analyze_time_series(
self,
data: pd.DataFrame,
metrics: List[str],
window: Optional[int] = None
) -> Dict[str, pd.Series]:
"""
Analyze time series data with rolling windows and custom metrics.
Args:
data: Time series data
metrics: List of metrics to calculate
window: Rolling window size
"""
results = {}
for metric in metrics:
if window:
result = data.rolling(window).agg(metric)
else:
result = data.agg(metric)
results[metric] = result
return resultsAdvanced API Usage
SDK Usage
from explainthis import ExplainThis, AnalysisContext
client = ExplainThis(api_key='your_api_key')
# Create analysis context
context = AnalysisContext(
imports=['pandas', 'numpy'],
related_code={
'config.py': 'Configuration settings',
'metrics.py': 'Custom metric definitions'
},
dependencies={
'pandas': '2.0.0',
'numpy': '1.24.0'
}
)
# Get detailed explanation
explanation = client.explain(
code=code,
mode='performance',
language='python',
context=context,
include_suggestions=True
)
print(explanation)Analysis Details
This example shows a data analysis class using pandas for time series processing. The code includes type hints, docstrings, and flexible configuration. The explanation request includes additional context about related files and dependencies, helping the analyzer provide more accurate and relevant explanations, including performance implications of pandas operations.
Security Analysis Mode
Analyze code for security vulnerabilities
Code to Analyze
Source Code
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const app = express();
app.use(express.json());
app.post('/api/auth', async (req, res) => {
const { username, password } = req.body;
try {
// Get user from database
const user = await db.collection('users')
.findOne({ username });
if (!user) {
return res.status(401).json({
error: 'Invalid credentials'
});
}
// Verify password
const valid = await bcrypt.compare(
password,
user.password
);
if (!valid) {
return res.status(401).json({
error: 'Invalid credentials'
});
}
// Generate token
const token = jwt.sign(
{ userId: user._id },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
res.json({ token });
} catch (error) {
res.status(500).json({
error: 'Internal server error'
});
}
});Advanced API Usage
SDK Usage
import { ExplainThis } from '@explainthis/sdk';
const explainThis = new ExplainThis(process.env.EXPLAINTHIS_API_KEY);
const securityAnalysis = await explainThis.explain({
code: code,
mode: 'security',
language: 'javascript',
options: {
checkDependencies: true,
scanVulnerabilities: true,
suggestFixes: true,
}
});
console.log('Security Analysis:');
console.log(securityAnalysis.vulnerabilities);
console.log('Suggested Fixes:');
console.log(securityAnalysis.fixes);Analysis Details
This authentication endpoint demonstrates several security considerations. The security analysis mode checks for: proper password hashing with bcrypt, JWT token generation, error handling that doesn't leak information, and environment variable usage for secrets. It also analyzes dependencies for known vulnerabilities and suggests security improvements.
Advanced Features
- Batch processing for analyzing multiple code snippets
- Context-aware analysis with related code and dependencies
- Security scanning and vulnerability detection
- Custom analysis options and configurations
- Performance optimization suggestions