Back to blog

Syntax Highlighting Test

·3 min read
#Test#Syntax#Code

Syntax Highlighting Test

This post tests syntax highlighting for various programming languages.

JavaScript

Javascript
// Function declaration
function calculateTotal(items) {
  const tax = 0.1;
  let total = 0;
  
  for (const item of items) {
    total += item.price * (1 + tax);
  }
  
  return total;
}

// Arrow function with destructuring
const processUser = ({ name, email, age }) => {
  console.log(`Processing user: ${name}`);
  return {
    id: Math.random(),
    name: name.toUpperCase(),
    email,
    isAdult: age >= 18
  };
};

// Async/await
async function fetchUserData(userId) {
  try {
    const response = await fetch(`/api/users/${userId}`);
    const userData = await response.json();
    return userData;
  } catch (error) {
    console.error('Failed to fetch user:', error);
    throw new Error('User not found');
  }
}

TypeScript

Javascript
interface User {
  id: number;
  name: string;
  email: string;
  isActive: boolean;
}

type UserRole = 'admin' | 'user' | 'moderator';

class UserService {
  private users: User[] = [];

  constructor(private apiUrl: string) {}

  async createUser(userData: Omit<User, 'id'>): Promise<User> {
    const newUser: User = {
      ...userData,
      id: Date.now()
    };
    
    this.users.push(newUser);
    return newUser;
  }

  findUsersByRole<T extends UserRole>(role: T): User[] {
    return this.users.filter(user => user.role === role);
  }
}

Python

Javascript
# Class definition
class Calculator:
    def __init__(self, precision=2):
        self.precision = precision
        self.history = []
    
    def add(self, a: float, b: float) -> float:
        """Add two numbers and store in history"""
        result = round(a + b, self.precision)
        self.history.append(f"{a} + {b} = {result}")
        return result
    
    def get_history(self) -> list:
        return self.history.copy()

# List comprehension and lambda
numbers = [1, 2, 3, 4, 5]
squared = [x**2 for x in numbers if x % 2 == 0]
filtered = list(filter(lambda x: x > 10, squared))

# Dictionary and string formatting
user_data = {
    'name': 'John Doe',
    'age': 30,
    'email': 'john@example.com'
}

message = f"Hello {user_data['name']}, you are {user_data['age']} years old"
print(message)

CSS

Javascript
/* Variables and modern CSS */
:root {
  --primary-color: #3b82f6;
  --secondary-color: #64748b;
  --border-radius: 0.5rem;
  --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

/* Grid layout */
.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
  padding: 2rem;
}

/* Flexbox and animations */
.card {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: var(--border-radius);
  box-shadow: var(--shadow);
  padding: 1.5rem;
  transition: transform 0.2s ease-in-out;
}

.card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px -8px rgba(0, 0, 0, 0.2);
}

/* Media queries */
@media (max-width: 768px) {
  .container {
    grid-template-columns: 1fr;
    padding: 1rem;
  }
}

Bash

Javascript
#!/bin/bash

# Variables
PROJECT_NAME="my-app"
BUILD_DIR="dist"
LOG_FILE="deploy.log"

# Functions
log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

deploy_app() {
    local environment=$1
    
    log_message "Starting deployment to $environment"
    
    # Build the project
    if npm run build; then
        log_message "Build successful"
    else
        log_message "Build failed"
        exit 1
    fi
    
    # Deploy based on environment
    case $environment in
        "production")
            rsync -avz "$BUILD_DIR/" user@prod-server:/var/www/html/
            ;;
        "staging")
            rsync -avz "$BUILD_DIR/" user@staging-server:/var/www/html/
            ;;
        *)
            log_message "Unknown environment: $environment"
            exit 1
            ;;
    esac
    
    log_message "Deployment to $environment completed"
}

# Main execution
if [ $# -eq 0 ]; then
    echo "Usage: $0 <environment>"
    echo "Available environments: production, staging"
    exit 1
fi

deploy_app "$1"

JSON

Javascript
{
  "name": "my-awesome-app",
  "version": "1.0.0",
  "description": "A sample application",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "build": "webpack --mode production",
    "test": "jest"
  },
  "dependencies": {
    "express": "^4.18.2",
    "lodash": "^4.17.21",
    "moment": "^2.29.4"
  },
  "devDependencies": {
    "nodemon": "^2.0.22",
    "jest": "^29.5.0",
    "webpack": "^5.82.1"
  },
  "keywords": ["node", "express", "api"],
  "author": "John Doe <john@example.com>",
  "license": "MIT"
}

This post demonstrates syntax highlighting across multiple programming languages!

You Might Also Like