New Feature: Superblog has syntax highlighting

Now you can use superblog for your developer-focused content!
Robust syntax highlighting is supported out of the box for 50 languages.

Behold! Your code is rendered in the popular Dracula theme using Prism.js.

A few supported languages

  1. Plain Text
  2. Bash
  3. C
  4. C++
  5. C#
  6. CSS
  7. Dart
  8. Diff
  9. Docker
  10. Elixir
  11. Elm
  12. Erlang
  13. Go
  14. GraphQL
  15. Haskell
  16. HTML
  17. HTTP
  18. Java
  19. JavaScript
  20. JSON
  21. JSX
  22. Julia
  23. Kotlin
  24. LaTeX
  25. Lua
  26. Markdown
  27. MATLAB
  28. Nginx
  29. Objective-C
  30. OCaml
  31. Perl
  32. PHP
  33. PowerShell
  34. Python
  35. R
  36. Ruby
  37. Rust
  38. Sass
  39. Scala
  40. SCSS
  41. Shell Session
  42. SQL
  43. Swift
  44. TOML
  45. TSX
  46. TypeScript
  47. Vim
  48. XML
  49. YAML
  50. Zig

Sample Demos

1. Bash

#!/bin/bash

# System monitoring script
echo "=== System Health Check ==="

# Check disk usage
DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}')
echo "Disk Usage: $DISK_USAGE"

# Check memory
FREE_MEM=$(free -h | grep "^Mem" | awk '{print $3 "/" $2}')
echo "Memory Usage: $FREE_MEM"

# Function to check service status
check_service() {
    if systemctl is-active --quiet "$1"; then
        echo "✓ $1 is running"
    else
        echo "✗ $1 is not running"
    fi
}

# Check critical services
services=("nginx" "postgresql" "redis")
for service in "${services[@]}"; do
    check_service "$service"
done

# Log results
date >> /var/log/health-check.log

2. CSS

/* Modern CSS with animations and variables */
:root {
--primary-color: #bd93f9;
--background: #282a36;
--foreground: #f8f8f2;
--comment: #6272a4;
--cyan: #8be9fd;
--green: #50fa7b;
--pink: #ff79c6;
}

/* Glassmorphism card component */
.card {
background: rgba(40, 42, 54, 0.8);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 2rem;
box-shadow:
0 8px 32px rgba(0, 0, 0, 0.3),
inset 0 1px 0 rgba(255, 255, 255, 0.1);
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.card:hover {
transform: translateY(-4px) scale(1.02);
}

/* Animated gradient button */
.btn-gradient {
background: linear-gradient(
45deg,
var(--pink),
var(--purple),
var(--cyan)
);
background-size: 200% 200%;
animation: gradient-shift 3s ease infinite;
}

@keyframes gradient-shift {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}

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

@container (min-width: 768px) {
.card {
padding: 3rem;
}
}

3. Go

package main

import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"time"
)

// User represents a user entity
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
CreatedAt time.Time `json:"created_at"`
}

// UserService handles user operations
type UserService struct {
mu sync.RWMutex
users map[string]*User
}

// NewUserService creates a new user service
func NewUserService() *UserService {
return &UserService{
users: make(map[string]*User),
}
}

// GetUser retrieves a user by ID
func (s *UserService) GetUser(ctx context.Context, id string) (*User, error) {
s.mu.RLock()
defer s.mu.RUnlock()

select {
case <-ctx.Done():
return nil, ctx.Err()
default:
if user, ok := s.users[id]; ok {
return user, nil
}
return nil, fmt.Errorf("user not found: %s", id)
}
}

// HTTP handler with middleware
func rateLimiter(next http.HandlerFunc) http.HandlerFunc {
limiter := make(chan struct{}, 10)

return func(w http.ResponseWriter, r *http.Request) {
select {
case limiter <- struct{}{}:
defer func() { <-limiter }()
next(w, r)
default:
http.Error(w, "Too many requests", http.StatusTooManyRequests)
}
}
}

func main() {
service := NewUserService()

http.HandleFunc("/api/users", rateLimiter(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"status": "ok",
"time": time.Now().Format(time.RFC3339),
})
}))

log.Printf("Server starting on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}

4. HTML

<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Modern web application with semantic HTML5">
<title>Syntax Highlighting Demo</title>
<link rel="stylesheet" href="/styles/main.css">
<script type="module" src="/js/app.js" defer></script>
</head>
<body>
<!-- Navigation with ARIA labels -->
<nav class="navbar" role="navigation" aria-label="main navigation">
<div class="nav-container">
<a href="/" class="nav-brand">
<img src="/logo.svg" alt="Logo" width="32" height="32">
<span>DevBlog</span>
</a>
<ul class="nav-menu">
<li><a href="/posts" aria-current="page">Posts</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</div>
</nav>

<!-- Main content with semantic HTML5 -->
<main class="container">
<article class="post" itemscope itemtype="https://schema.org/BlogPosting">
<header>
<h1 itemprop="headline">Implementing Syntax Highlighting</h1>
<time datetime="2025-01-15" itemprop="datePublished">
January 15, 2025
</time>
</header>

<section itemprop="articleBody">
<p>This article demonstrates various programming languages...</p>

<!-- Interactive code demo -->
<div class="code-demo" data-language="javascript">
<pre><code class="language-javascript">
console.log("Hello, Dracula!");
</code></pre>
<button onclick="copyCode(this)" aria-label="Copy code">
<svg><!-- Copy icon --></svg>
</button>
</div>
</section>

<!-- Comments section -->
<section class="comments" aria-labelledby="comments-heading">
<h2 id="comments-heading">Comments</h2>
<form class="comment-form" method="POST" action="/api/comments">
<label for="comment">Your comment:</label>
<textarea id="comment" name="comment" required></textarea>
<button type="submit">Post Comment</button>
</form>
</section>
</article>
</main>

<!-- Footer with microdata -->
<footer class="site-footer">
<p>&copy; 2025 DevBlog. All rights reserved.</p>
</footer>
</body>
</html>

5. Java

package com.example.blog;

import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

// Main blog post entity
public class BlogPost {
private final String id;
private String title;
private String content;
private Set<String> tags;
private LocalDateTime publishedAt;
private AtomicInteger viewCount;

public BlogPost(String title, String content) {
this.id = UUID.randomUUID().toString();
this.title = title;
this.content = content;
this.tags = new HashSet<>();
this.publishedAt = LocalDateTime.now();
this.viewCount = new AtomicInteger(0);
}

// Builder pattern for complex objects
public static class Builder {
private String title;
private String content;
private Set<String> tags = new HashSet<>();

public Builder title(String title) {
this.title = title;
return this;
}

public Builder content(String content) {
this.content = content;
return this;
}

public Builder addTag(String tag) {
this.tags.add(tag);
return this;
}

public BlogPost build() {
BlogPost post = new BlogPost(title, content);
post.tags = this.tags;
return post;
}
}

// Async processing with CompletableFuture
public CompletableFuture<String> processContentAsync() {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000); // Simulate processing
return content.toLowerCase()
.replaceAll("[^a-z0-9\\s]", "")
.trim();
} catch (InterruptedException e) {
throw new CompletionException(e);
}
});
}

// Stream API usage
public Map<String, Long> getWordFrequency() {
return Arrays.stream(content.split("\\s+"))
.map(String::toLowerCase)
.filter(word -> word.length() > 3)
.collect(Collectors.groupingBy(
word -> word,
Collectors.counting()
));
}

// Thread-safe view increment
public int incrementAndGetViews() {
return viewCount.incrementAndGet();
}

@Override
public String toString() {
return String.format("BlogPost{id='%s', title='%s', views=%d, published=%s}",
id, title, viewCount.get(),
publishedAt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
}
}

// Service class with dependency injection
@Service
@Transactional
public class BlogService {
private final BlogRepository repository;
private final CacheManager cacheManager;

@Autowired
public BlogService(BlogRepository repository, CacheManager cacheManager) {
this.repository = repository;
this.cacheManager = cacheManager;
}

@Cacheable("posts")
public Optional<BlogPost> findById(String id) {
return repository.findById(id);
}

public List<BlogPost> searchPosts(String query) {
return repository.findAll().stream()
.filter(post -> post.getTitle().contains(query) ||
post.getContent().contains(query))
.sorted(Comparator.comparing(BlogPost::getPublishedAt).reversed())
.limit(10)
.collect(Collectors.toList());
}
}

6. JavaScript

// Modern JavaScript with ES6+ features
class SyntaxHighlighter {
constructor(theme = 'dracula') {
this.theme = theme;
this.languages = new Map();
this.cache = new WeakMap();
this.initializeLanguages();
}

// Async language loading
async initializeLanguages() {
const languages = ['javascript', 'python', 'rust', 'go'];

const loadPromises = languages.map(async (lang) => {
try {
const module = await import(`./languages/${lang}.js`);
this.languages.set(lang, module.default);
console.log(`✓ Loaded ${lang}`);
} catch (error) {
console.error(`✗ Failed to load ${lang}:`, error);
}
});

await Promise.allSettled(loadPromises);
}

// Highlight code with memoization
highlight(code, language) {
if (this.cache.has(code)) {
return this.cache.get(code);
}

const highlighted = this.processCode(code, language);
this.cache.set(code, highlighted);
return highlighted;
}

// Process code with regex patterns
processCode(code, language) {
const patterns = {
comment: /\/\/.*$|\/\*[\s\S]*?\*\//gm,
string: /(['"`])(?:(?=(\\?))\2.)*?\1/g,
keyword: /\b(const|let|var|function|class|async|await|if|else|for|while|return)\b/g,
number: /\b\d+\.?\d*\b/g,
function: /\b\w+(?=\()/g,
};

let processed = code;

for (const [type, pattern] of Object.entries(patterns)) {
processed = processed.replace(pattern, (match) =>
`<span class="token ${type}">${match}</span>`
);
}

return processed;
}

// Debounced live highlighting
setupLiveHighlighting(editor, preview) {
let timeoutId;

const debounce = (func, delay = 300) => {
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
};

const updatePreview = debounce((event) => {
const code = event.target.value;
const language = editor.dataset.language || 'javascript';
preview.innerHTML = this.highlight(code, language);
});

editor.addEventListener('input', updatePreview);
}

// Intersection Observer for lazy loading
observeCodeBlocks() {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const block = entry.target;
const language = block.dataset.language;
const code = block.textContent;

block.innerHTML = this.highlight(code, language);
observer.unobserve(block);
}
});
},
{ rootMargin: '100px' }
);

document.querySelectorAll('pre code[data-language]')
.forEach(block => observer.observe(block));
}
}

// Usage with async/await
(async () => {
const highlighter = new SyntaxHighlighter('dracula');

// Wait for languages to load
await new Promise(resolve => setTimeout(resolve, 1000));

// Apply highlighting
highlighter.observeCodeBlocks();

// Copy button functionality
document.querySelectorAll('.copy-btn').forEach(btn => {
btn.addEventListener('click', async (e) => {
const code = e.target.parentElement.querySelector('code').textContent;

try {
await navigator.clipboard.writeText(code);
btn.textContent = '✓ Copied!';
setTimeout(() => btn.textContent = 'Copy', 2000);
} catch (err) {
console.error('Copy failed:', err);
}
});
});
})();

// Export for module usage
export default SyntaxHighlighter;

7. JSON

{
"name": "syntax-highlighter-demo",
"version": "2.1.0",
"description": "A modern syntax highlighting implementation with Dracula theme",
"author": {
"name": "Dev Developer",
"email": "[email protected]",
"url": "https://devblog.example.com"
},
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "vitest",
"lint": "eslint . --ext .js,.ts",
"format": "prettier --write ."
},
"dependencies": {
"prismjs": "^1.29.0",
"prism-themes": "^1.9.0"
},
"devDependencies": {
"@types/prismjs": "^1.26.0",
"vite": "^5.0.0",
"vitest": "^1.2.0",
"eslint": "^8.56.0",
"prettier": "^3.2.0",
"typescript": "^5.3.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/username/syntax-highlighter.git"
},
"keywords": [
"syntax-highlighting",
"prismjs",
"dracula-theme",
"code-formatter",
"developer-tools"
],
"config": {
"theme": "dracula",
"languages": [
"javascript",
"typescript",
"python",
"rust",
"go",
"java",
"bash",
"sql",
"css",
"html",
"json"
],
"plugins": {
"lineNumbers": true,
"copyButton": true,
"showLanguage": true,
"autoloader": false
}
},
"prettier": {
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always"
},
"eslintConfig": {
"extends": ["eslint:recommended"],
"env": {
"browser": true,
"es2022": true,
"node": true
},
"parserOptions": {
"ecmaVersion": 2022,
"sourceType": "module"
}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
],
"license": "MIT"
}

8. Python

#!/usr/bin/env python3
"""
Syntax highlighting demo with modern Python features
"""

import asyncio
import json
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum, auto
from pathlib import Path
from typing import Dict, List, Optional, Union, AsyncIterator
import aiohttp
from functools import lru_cache, wraps
import time

# Enum for language types
class Language(Enum):
PYTHON = auto()
JAVASCRIPT = auto()
RUST = auto()
GO = auto()

@classmethod
def from_extension(cls, ext: str) -> Optional['Language']:
mapping = {
'.py': cls.PYTHON,
'.js': cls.JAVASCRIPT,
'.rs': cls.RUST,
'.go': cls.GO,
}
return mapping.get(ext)

# Dataclass with type hints
@dataclass
class CodeBlock:
content: str
language: Language
line_numbers: bool = True
theme: str = "dracula"
metadata: Dict[str, any] = field(default_factory=dict)
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))

def __post_init__(self):
self.lines = self.content.count('\n') + 1
self.size_bytes = len(self.content.encode('utf-8'))

@property
def is_large(self) -> bool:
return self.lines > 100 or self.size_bytes > 10_000

# Async context manager for file operations
class AsyncFileHandler:
def __init__(self, filepath: Path):
self.filepath = filepath
self.file = None

async def __aenter__(self):
self.file = await asyncio.to_thread(open, self.filepath, 'r')
return self.file

async def __aexit__(self, exc_type, exc_val, exc_tb):
if self.file:
await asyncio.to_thread(self.file.close)

# Decorator for performance monitoring
def time_it(func):
@wraps(func)
async def async_wrapper(*args, **kwargs):
start = time.perf_counter()
result = await func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"⏱️ {func.__name__} took {elapsed:.3f}s")
return result

@wraps(func)
def sync_wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"⏱️ {func.__name__} took {elapsed:.3f}s")
return result

return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper

# Main highlighter class
class SyntaxHighlighter:
def __init__(self, theme: str = "dracula"):
self.theme = theme
self.session: Optional[aiohttp.ClientSession] = None

async def __aenter__(self):
self.session = aiohttp.ClientSession()
return self

async def __aexit__(self, *args):
if self.session:
await self.session.close()

@lru_cache(maxsize=128)
def get_theme_colors(self) -> Dict[str, str]:
"""Cached theme colors"""
themes = {
"dracula": {
"background": "#282a36",
"foreground": "#f8f8f2",
"comment": "#6272a4",
"cyan": "#8be9fd",
"green": "#50fa7b",
"orange": "#ffb86c",
"pink": "#ff79c6",
"purple": "#bd93f9",
"red": "#ff5555",
"yellow": "#f1fa8c"
}
}
return themes.get(self.theme, themes["dracula"])

@time_it
async def highlight_file(self, filepath: Path) -> str:
"""Async file highlighting"""
async with AsyncFileHandler(filepath) as file:
content = await asyncio.to_thread(file.read)

language = Language.from_extension(filepath.suffix)
if not language:
raise ValueError(f"Unsupported file type: {filepath.suffix}")

code_block = CodeBlock(content, language)
return await self.process_highlighting(code_block)

async def process_highlighting(self, block: CodeBlock) -> str:
"""Process syntax highlighting asynchronously"""
# Simulate async processing
await asyncio.sleep(0.1)

colors = self.get_theme_colors()
lines = block.content.split('\n')

highlighted = []
for i, line in enumerate(lines, 1):
if block.line_numbers:
line_num = f'<span class="line-number">{i:4d}</span> '
else:
line_num = ''

# Simple token highlighting (demonstration)
line = self._highlight_tokens(line, colors)
highlighted.append(f'{line_num}{line}')

return '\n'.join(highlighted)

def _highlight_tokens(self, line: str, colors: Dict[str, str]) -> str:
"""Apply syntax highlighting to tokens"""
# Python-specific keywords
keywords = ['def', 'class', 'async', 'await', 'import', 'from',
'if', 'else', 'elif', 'for', 'while', 'return',
'try', 'except', 'finally', 'with', 'as']

for keyword in keywords:
line = line.replace(f' {keyword} ',
f' <span style="color: {colors["pink"]}">{keyword}</span> ')

# Highlight strings (simple version)
import re
line = re.sub(r'(["\'])([^"\']*)\1',
rf'<span style="color: {colors["yellow"]}">\1\2\1</span>',
line)

# Highlight comments
if '#' in line:
comment_start = line.index('#')
line = (line[:comment_start] +
f'<span style="color: {colors["comment"]}">{line[comment_start:]}</span>')

return line

async def batch_highlight(self, files: List[Path]) -> AsyncIterator[str]:
"""Yield highlighted files as they complete"""
tasks = [self.highlight_file(file) for file in files]

for coro in asyncio.as_completed(tasks):
result = await coro
yield result

# Example usage
async def main():
files_to_highlight = [
Path("example.py"),
Path("script.js"),
Path("main.rs"),
]

async with SyntaxHighlighter("dracula") as highlighter:
# Single file
if files_to_highlight[0].exists():
result = await highlighter.highlight_file(files_to_highlight[0])
print(f"Highlighted {files_to_highlight[0].name}")

# Batch processing
async for highlighted in highlighter.batch_highlight(files_to_highlight):
print(f"Processed file with {len(highlighted)} characters")

if __name__ == "__main__":
# Python 3.7+ required
asyncio.run(main())

9. Rust

// Advanced Rust showcasing modern features and patterns
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, RwLock};
use std::marker::PhantomData;
use std::time::{Duration, Instant};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use thiserror::Error;

/// Custom error types with thiserror
#[derive(Error, Debug)]
pub enum BlogError {
    #[error("Post not found: {id}")]
    PostNotFound { id: String },
    
    #[error("Database error: {0}")]
    Database(#[from] sqlx::Error),
    
    #[error("Validation failed: {message}")]
    Validation { message: String },
    
    #[error("Rate limit exceeded, retry after {retry_after:?}")]
    RateLimited { retry_after: Duration },
    
    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

/// Generic type with phantom data and lifetime bounds
pub struct Cache<'a, K, V, S = RandomState> 
where
    K: Eq + Hash + Clone,
    V: Clone,
{
    storage: Arc<RwLock<HashMap<K, CacheEntry<V>, S>>>,
    ttl: Duration,
    max_size: usize,
    _phantom: PhantomData<&'a ()>,
}

#[derive(Clone)]
struct CacheEntry<V> {
    value: V,
    expires_at: Instant,
    access_count: usize,
}

impl<'a, K, V, S> Cache<'a, K, V, S>
where
    K: Eq + Hash + Clone + Send + Sync + 'static,
    V: Clone + Send + Sync + 'static,
    S: BuildHasher + Default,
{
    /// Creates a new cache with TTL and size limit
    pub fn new(ttl: Duration, max_size: usize) -> Self {
        Self {
            storage: Arc::new(RwLock::new(HashMap::default())),
            ttl,
            max_size,
            _phantom: PhantomData,
        }
    }
    
    /// Get value with automatic expiry check
    pub async fn get(&self, key: &K) -> Option<V> {
        let mut storage = self.storage.write().unwrap();
        
        if let Some(entry) = storage.get_mut(key) {
            if entry.expires_at > Instant::now() {
                entry.access_count += 1;
                return Some(entry.value.clone());
            } else {
                storage.remove(key);
            }
        }
        None
    }
    
    /// Insert with LRU eviction if needed
    pub async fn insert(&self, key: K, value: V) {
        let mut storage = self.storage.write().unwrap();
        
        // Evict least recently used if at capacity
        if storage.len() >= self.max_size {
            if let Some(lru_key) = storage
                .iter()
                .min_by_key(|(_, entry)| entry.access_count)
                .map(|(k, _)| k.clone())
            {
                storage.remove(&lru_key);
            }
        }
        
        storage.insert(
            key,
            CacheEntry {
                value,
                expires_at: Instant::now() + self.ttl,
                access_count: 0,
            },
        );
    }
}

/// Trait with async methods using async-trait
#[async_trait]
pub trait Repository: Send + Sync {
    type Entity;
    type Error;
    
    async fn find_by_id(&self, id: &str) -> Result<Option<Self::Entity>, Self::Error>;
    async fn save(&self, entity: &Self::Entity) -> Result<(), Self::Error>;
    async fn delete(&self, id: &str) -> Result<bool, Self::Error>;
    
    /// Default implementation with where clause
    async fn exists(&self, id: &str) -> Result<bool, Self::Error>
    where
        Self::Entity: Send,
    {
        Ok(self.find_by_id(id).await?.is_some())
    }
}

/// Zero-cost abstraction with const generics
#[derive(Debug, Clone)]
pub struct FixedBuffer<T, const N: usize> {
    buffer: [Option<T>; N],
    head: usize,
    tail: usize,
    len: usize,
}

impl<T: Clone, const N: usize> FixedBuffer<T, N> {
    /// Const function for compile-time initialization
    pub const fn new() -> Self {
        Self {
            buffer: [const { None }; N],
            head: 0,
            tail: 0,
            len: 0,
        }
    }
    
    /// Push with compile-time bounds checking
    pub fn push(&mut self, item: T) -> Result<(), T> {
        if self.len >= N {
            return Err(item);
        }
        
        self.buffer[self.tail] = Some(item);
        self.tail = (self.tail + 1) % N;
        self.len += 1;
        Ok(())
    }
    
    /// Pop from front
    pub fn pop(&mut self) -> Option<T> {
        if self.len == 0 {
            return None;
        }
        
        let item = self.buffer[self.head].take();
        self.head = (self.head + 1) % N;
        self.len -= 1;
        item
    }
}

10. SQL

-- Advanced SQL queries demonstrating various features
-- Database: PostgreSQL 15+

-- Create schema and tables with constraints
CREATE SCHEMA IF NOT EXISTS blog_system;

SET search_path TO blog_system, public;

-- Users table with advanced constraints
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
metadata JSONB DEFAULT '{}',
is_active BOOLEAN DEFAULT true,

CONSTRAINT email_format CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$'),
CONSTRAINT username_length CHECK (LENGTH(username) >= 3)
);

-- Create indexes for performance
CREATE INDEX idx_users_email ON users USING btree(email);
CREATE INDEX idx_users_metadata ON users USING gin(metadata);
CREATE INDEX idx_users_created ON users(created_at DESC);

-- Posts table with full-text search
CREATE TABLE posts (
id BIGSERIAL PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
slug VARCHAR(255) UNIQUE NOT NULL,
content TEXT NOT NULL,
tags TEXT[] DEFAULT ARRAY[]::TEXT[],
status VARCHAR(20) DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'archived')),
view_count INTEGER DEFAULT 0,
published_at TIMESTAMPTZ,
search_vector tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', COALESCE(title, '')), 'A') ||
setweight(to_tsvector('english', COALESCE(content, '')), 'B')
) STORED,

created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

-- Full-text search index
CREATE INDEX idx_posts_search ON posts USING gin(search_vector);
CREATE INDEX idx_posts_tags ON posts USING gin(tags);

-- Comments table with recursive structure
CREATE TABLE comments (
id BIGSERIAL PRIMARY KEY,
post_id BIGINT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id),
parent_id BIGINT REFERENCES comments(id) ON DELETE CASCADE,
content TEXT NOT NULL,
is_edited BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,

-- Prevent deep nesting
CONSTRAINT max_depth CHECK (
(SELECT COUNT(*) FROM comments c
WHERE c.id = parent_id) < 3
)
);

-- Analytics table for time-series data
CREATE TABLE post_analytics (
post_id BIGINT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
date DATE NOT NULL,
views INTEGER DEFAULT 0,
unique_visitors INTEGER DEFAULT 0,
avg_time_seconds NUMERIC(10,2),
bounce_rate NUMERIC(5,2),

PRIMARY KEY (post_id, date)
) PARTITION BY RANGE (date);

-- Create monthly partitions
CREATE TABLE post_analytics_2025_01 PARTITION OF post_analytics
FOR VALUES FROM ('2025-01-01') TO ('2025-02-01');

-- Common Table Expression (CTE) for trending posts
WITH trending_posts AS (
SELECT
p.id,
p.title,
p.slug,
u.username AS author,
COUNT(DISTINCT c.id) AS comment_count,
COALESCE(SUM(pa.views), 0) AS total_views,

-- Calculate trend score
(COUNT(DISTINCT c.id) * 2 + COALESCE(SUM(pa.views), 0) / 100)
* EXP(-0.1 * EXTRACT(EPOCH FROM (NOW() - p.published_at)) / 86400) AS trend_score

FROM posts p
INNER JOIN users u ON p.user_id = u.id
LEFT JOIN comments c ON p.id = c.post_id
LEFT JOIN post_analytics pa ON p.id = pa.post_id
AND pa.date >= CURRENT_DATE - INTERVAL '7 days'
WHERE
p.status = 'published'
AND p.published_at >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY p.id, p.title, p.slug, u.username, p.published_at
),
ranked_posts AS (
SELECT
*,
ROW_NUMBER() OVER (ORDER BY trend_score DESC) AS rank,
PERCENT_RANK() OVER (ORDER BY trend_score DESC) AS percentile
FROM trending_posts
)
SELECT
rank,
title,
author,
comment_count,
total_views,
ROUND(trend_score::NUMERIC, 2) AS score,
CASE
WHEN percentile <= 0.1 THEN '🔥 Hot'
WHEN percentile <= 0.3 THEN '📈 Trending'
ELSE '📊 Active'
END AS status
FROM ranked_posts
WHERE rank <= 10
ORDER BY rank;

-- Window functions for analytics
SELECT
DATE_TRUNC('day', created_at) AS day,
COUNT(*) AS daily_posts,
SUM(COUNT(*)) OVER (ORDER BY DATE_TRUNC('day', created_at)) AS cumulative_posts,
AVG(COUNT(*)) OVER (
ORDER BY DATE_TRUNC('day', created_at)
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_avg_7d,
LAG(COUNT(*), 7) OVER (ORDER BY DATE_TRUNC('day', created_at)) AS same_day_last_week,

-- Calculate week-over-week growth
CASE
WHEN LAG(COUNT(*), 7) OVER (ORDER BY DATE_TRUNC('day', created_at)) > 0
THEN ROUND(
((COUNT(*)::NUMERIC - LAG(COUNT(*), 7) OVER (ORDER BY DATE_TRUNC('day', created_at)))
/ LAG(COUNT(*), 7) OVER (ORDER BY DATE_TRUNC('day', created_at))) * 100,
2
)
ELSE NULL
END AS wow_growth_percent

FROM posts
WHERE created_at >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY DATE_TRUNC('day', created_at);

-- Recursive query for comment threads
WITH RECURSIVE comment_tree AS (
-- Base case: top-level comments
SELECT
c.id,
c.post_id,
c.content,
c.created_at,
u.username,
0 AS depth,
ARRAY[c.id] AS path,
c.id::TEXT AS thread_path
FROM comments c
JOIN users u ON c.user_id = u.id
WHERE c.parent_id IS NULL

UNION ALL

-- Recursive case: nested comments
SELECT
c.id,
c.post_id,
c.content,
c.created_at,
u.username,
ct.depth + 1,
ct.path || c.id,
ct.thread_path || '.' || c.id::TEXT
FROM comments c
JOIN users u ON c.user_id = u.id
JOIN comment_tree ct ON c.parent_id = ct.id
WHERE ct.depth < 3 -- Limit recursion depth
)
SELECT
REPEAT(' ', depth) || '└─ ' || username AS comment_tree,
content,
created_at
FROM comment_tree
WHERE post_id = 123
ORDER BY thread_path;

-- Advanced JSON operations
UPDATE users
SET metadata = jsonb_set(
metadata,
'{preferences}',
metadata->'preferences' || '{"theme": "dracula", "notifications": true}'::JSONB,
true
)
WHERE
metadata->>'last_login' < (CURRENT_DATE - INTERVAL '30 days')::TEXT
AND metadata->'preferences'->>'theme' IS NULL;

-- Create materialized view for performance
CREATE MATERIALIZED VIEW mv_user_stats AS
SELECT
u.id,
u.username,
COUNT(DISTINCT p.id) AS post_count,
COUNT(DISTINCT c.id) AS comment_count,
COALESCE(SUM(p.view_count), 0) AS total_views,
MAX(p.published_at) AS last_post_date,

-- Calculate engagement score
(COUNT(DISTINCT p.id) * 10 +
COUNT(DISTINCT c.id) * 2 +
LOG(GREATEST(SUM(p.view_count), 1))) AS engagement_score

FROM users u
LEFT JOIN posts p ON u.id = p.user_id AND p.status = 'published'
LEFT JOIN comments c ON u.id = c.user_id
GROUP BY u.id, u.username
WITH DATA;

-- Create index on materialized view
CREATE INDEX idx_mv_user_stats_score ON mv_user_stats(engagement_score DESC);

-- Refresh materialized view
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_user_stats;

11. TypeScript

// Advanced TypeScript with modern features and patterns

// Generic type constraints and conditional types
type DeepReadonly<T> = T extends (infer U)[]
? ReadonlyArray<DeepReadonly<U>>
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;

// Branded types for type safety
type UserId = string & { __brand: "UserId" };
type PostId = string & { __brand: "PostId" };

// Utility types and template literal types
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
type ApiEndpoint = `/api/${string}`;
type RouteParams<T extends string> = T extends `${infer _Start}:${infer Param}/${infer Rest}`
? { [K in Param | keyof RouteParams<Rest>]: string }
: T extends `${infer _Start}:${infer Param}`
? { [K in Param]: string }
: {};

// Advanced interface with index signatures and mapped types
interface BlogConfig {
readonly apiUrl: ApiEndpoint;
readonly theme: "light" | "dark" | "dracula";
readonly features: {
[K in "comments" | "search" | "analytics"]?: {
enabled: boolean;
config?: Record<string, unknown>;
};
};
readonly metadata: DeepReadonly<{
version: string;
author: string;
tags: string[];
}>;
}

// Discriminated unions with exhaustive checking
type AsyncState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };

function assertNever(x: never): never {
throw new Error(`Unexpected object: ${x}`);
}

// Class with decorators and private fields
function Logger(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;

descriptor.value = async function(...args: any[]) {
console.log(`[${new Date().toISOString()}] Calling ${propertyKey}`);
try {
const result = await original.apply(this, args);
console.log(`[${new Date().toISOString()}] Success: ${propertyKey}`);
return result;
} catch (error) {
console.error(`[${new Date().toISOString()}] Error in ${propertyKey}:`, error);
throw error;
}
};

return descriptor;
}

class BlogService {
#cache = new Map<string, unknown>();

constructor(private readonly config: BlogConfig) {}

@Logger
async fetchPost(id: PostId): Promise<Post> {
const cached = this.#cache.get(id);
if (cached) return cached as Post;

const response = await fetch(`${this.config.apiUrl}/posts/${id}`);
const post = await response.json();

this.#cache.set(id, post);
return post;
}

// Method overloading
async search(query: string): Promise<Post[]>;
async search(query: string, options: SearchOptions): Promise<SearchResult>;
async search(query: string, options?: SearchOptions): Promise<Post[] | SearchResult> {
const endpoint = `${this.config.apiUrl}/search` as ApiEndpoint;

if (options?.detailed) {
return this.performDetailedSearch(query, options);
}

return this.performSimpleSearch(query);
}

private async performSimpleSearch(query: string): Promise<Post[]> {
// Implementation
return [];
}

private async performDetailedSearch(
query: string,
options: SearchOptions
): Promise<SearchResult> {
// Implementation
return { posts: [], total: 0, facets: {} };
}
}

// Complex type inference with generics
class StateManager<TState extends Record<string, unknown>> {
private state: TState;
private listeners = new Set<(state: TState) => void>();

constructor(initialState: TState) {
this.state = { ...initialState };
}

// Type-safe selectors with dot notation
get<K extends keyof TState>(key: K): TState[K];
get<K extends keyof TState, P extends keyof TState[K]>(
key: K,
prop: P
): TState[K][P];
get<K extends keyof TState, P extends keyof TState[K]>(
key: K,
prop?: P
): TState[K] | TState[K][P] {
if (prop !== undefined) {
return (this.state[key] as any)[prop];
}
return this.state[key];
}

// Partial state updates with type safety
update<K extends keyof TState>(
updates: Partial<TState> | ((prev: TState) => Partial<TState>)
): void {
const newValues = typeof updates === "function"
? updates(this.state)
: updates;

this.state = { ...this.state, ...newValues };
this.notify();
}

private notify(): void {
this.listeners.forEach(listener => listener(this.state));
}

subscribe(listener: (state: TState) => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
}

// Async generator with TypeScript
async function* paginatedFetch<T>(
endpoint: ApiEndpoint,
pageSize: number = 10
): AsyncGenerator<T[], void, unknown> {
let page = 0;
let hasMore = true;

while (hasMore) {
const response = await fetch(
`${endpoint}?page=${page}&size=${pageSize}`
);
const data = await response.json();

yield data.items as T[];

hasMore = data.hasNextPage;
page++;
}
}

// Using mapped types and conditional types together
type ApiResponse<T> = {
data: T;
meta: {
timestamp: number;
version: string;
};
};

type ApiClient = {
[K in HttpMethod as Lowercase<K>]: <TResponse = unknown>(
url: ApiEndpoint,
options?: RequestInit
) => Promise<ApiResponse<TResponse>>;
};

// Implementation with type guards
function isPost(item: Post | Comment): item is Post {
return "title" in item && "slug" in item;
}

function isComment(item: Post | Comment): item is Comment {
return "postId" in item && !("title" in item);
}

// Advanced async patterns
class AsyncQueue<T> {
private queue: T[] = [];
private resolvers: ((value: T) => void)[] = [];

async enqueue(item: T): Promise<void> {
if (this.resolvers.length > 0) {
const resolve = this.resolvers.shift()!;
resolve(item);
} else {
this.queue.push(item);
}
}

async dequeue(): Promise<T> {
if (this.queue.length > 0) {
return this.queue.shift()!;
}

return new Promise<T>(resolve => {
this.resolvers.push(resolve);
});
}

async *[Symbol.asyncIterator](): AsyncIterator<T> {
while (true) {
yield await this.dequeue();
}
}
}

// Module augmentation
declare global {
interface Window {
syntaxHighlighter: {
theme: string;
highlight: (code: string, language: string) => string;
};
}
}

// Namespace with complex types
namespace BlogSystem {
export interface Post {
id: PostId;
title: string;
slug: string;
content: string;
author: User;
tags: readonly string[];
publishedAt?: Date;
metadata: Record<string, unknown>;
}

export interface Comment {
id: string;
postId: PostId;
userId: UserId;
content: string;
createdAt: Date;
}

export interface User {
id: UserId;
username: string;
email: string;
role: "admin" | "editor" | "reader";
}

export interface SearchOptions {
detailed?: boolean;
filters?: Partial<Post>;
limit?: number;
offset?: number;
}

export interface SearchResult {
posts: Post[];
total: number;
facets: Record<string, number>;
}
}

// Re-export for module usage
export type { BlogConfig, AsyncState, ApiClient, BlogSystem };
export { BlogService, StateManager, AsyncQueue, paginatedFetch };

Want an SEO-focused and blazing fast blog?

Superblog let's you focus on writing content instead of optimizations.

Sai Krishna

Sai Krishna
Sai Krishna is the Founder and CEO of Superblog. Having built multiple products that scaled to tens of millions of users with only SEO and ASO, Sai Krishna is now building a blogging platform to help others grow organically.

superblog

Superblog is a blazing fast blogging platform for beautiful reading and writing experiences. Superblog takes care of SEO audits and site optimizations automatically.