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>
&lt;!-- Main content with semantic HTML5 --&gt;
&lt;main class=&#34;container&#34;&gt;
    &lt;article class=&#34;post&#34; itemscope itemtype=&#34;https://schema.org/BlogPosting&#34;&gt;
        &lt;header&gt;
            &lt;h1 itemprop=&#34;headline&#34;&gt;Implementing Syntax Highlighting&lt;/h1&gt;
            &lt;time datetime=&#34;2025-01-15&#34; itemprop=&#34;datePublished&#34;&gt;
                January 15, 2025
            &lt;/time&gt;
        &lt;/header&gt;
        
        &lt;section itemprop=&#34;articleBody&#34;&gt;
            &lt;p&gt;This article demonstrates various programming languages...&lt;/p&gt;
            
            &lt;!-- Interactive code demo --&gt;
            &lt;div class=&#34;code-demo&#34; data-language=&#34;javascript&#34;&gt;
                &lt;pre&gt;&lt;code class=&#34;language-javascript&#34;&gt;
                    console.log(&#34;Hello, Dracula!&#34;);
                &lt;/code&gt;&lt;/pre&gt;
                &lt;button onclick=&#34;copyCode(this)&#34; aria-label=&#34;Copy code&#34;&gt;
                    &lt;svg&gt;&lt;!-- Copy icon --&gt;&lt;/svg&gt;
                &lt;/button&gt;
            &lt;/div&gt;
        &lt;/section&gt;
        
        &lt;!-- Comments section --&gt;
        &lt;section class=&#34;comments&#34; aria-labelledby=&#34;comments-heading&#34;&gt;
            &lt;h2 id=&#34;comments-heading&#34;&gt;Comments&lt;/h2&gt;
            &lt;form class=&#34;comment-form&#34; method=&#34;POST&#34; action=&#34;/api/comments&#34;&gt;
                &lt;label for=&#34;comment&#34;&gt;Your comment:&lt;/label&gt;
                &lt;textarea id=&#34;comment&#34; name=&#34;comment&#34; required&gt;&lt;/textarea&gt;
                &lt;button type=&#34;submit&#34;&gt;Post Comment&lt;/button&gt;
            &lt;/form&gt;
        &lt;/section&gt;
    &lt;/article&gt;
&lt;/main&gt;

&lt;!-- Footer with microdata --&gt;
&lt;footer class=&#34;site-footer&#34;&gt;
    &lt;p&gt;&amp;copy; 2025 DevBlog. All rights reserved.&lt;/p&gt;
&lt;/footer&gt;

</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&lt;&gt;();
    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&lt;String&gt; tags = new HashSet&lt;&gt;();
    
    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&lt;String&gt; processContentAsync() {
    return CompletableFuture.supplyAsync(() -&gt; {
        try {
            Thread.sleep(1000); // Simulate processing
            return content.toLowerCase()
                .replaceAll(&#34;&#91;^a-z0-9\\s&#93;&#34;, &#34;&#34;)
                .trim();
        } catch (InterruptedException e) {
            throw new CompletionException(e);
        }
    });
}

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

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

@Override
public String toString() {
    return String.format(&#34;BlogPost{id=&#39;%s&#39;, title=&#39;%s&#39;, views=%d, published=%s}&#34;,
        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(&#34;posts&#34;)
public Optional&lt;BlogPost&gt; findById(String id) {
    return repository.findById(id);
}

public List&lt;BlogPost&gt; searchPosts(String query) {
    return repository.findAll().stream()
        .filter(post -&gt; 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 = &#91;&#39;javascript&#39;, &#39;python&#39;, &#39;rust&#39;, &#39;go&#39;&#93;;
    
    const loadPromises = languages.map(async (lang) =&gt; {
        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: /\/\/.*$|\/\*&#91;\s\S&#93;*?\*\//gm,
        string: /(&#91;&#39;&#34;`&#93;)(?:(?=(\\?))\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 &#91;type, pattern&#93; of Object.entries(patterns)) {
        processed = processed.replace(pattern, (match) =&gt; 
            `&lt;span class=&#34;token ${type}&#34;&gt;${match}&lt;/span&gt;`
        );
    }
    
    return processed;
}

// Debounced live highlighting
setupLiveHighlighting(editor, preview) {
    let timeoutId;
    
    const debounce = (func, delay = 300) =&gt; {
        return (...args) =&gt; {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() =&gt; func.apply(this, args), delay);
        };
    };
    
    const updatePreview = debounce((event) =&gt; {
        const code = event.target.value;
        const language = editor.dataset.language || &#39;javascript&#39;;
        preview.innerHTML = this.highlight(code, language);
    });
    
    editor.addEventListener(&#39;input&#39;, updatePreview);
}

// Intersection Observer for lazy loading
observeCodeBlocks() {
    const observer = new IntersectionObserver(
        (entries) =&gt; {
            entries.forEach(entry =&gt; {
                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: &#39;100px&#39; }
    );
    
    document.querySelectorAll(&#39;pre code&#91;data-language&#93;&#39;)
        .forEach(block =&gt; observer.observe(block));
}

}

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

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

// Apply highlighting
highlighter.observeCodeBlocks();

// Copy button functionality
document.querySelectorAll(&#39;.copy-btn&#39;).forEach(btn =&gt; {
    btn.addEventListener(&#39;click&#39;, async (e) =&gt; {
        const code = e.target.parentElement.querySelector(&#39;code&#39;).textContent;
        
        try {
            await navigator.clipboard.writeText(code);
            btn.textContent = &#39;✓ Copied!&#39;;
            setTimeout(() =&gt; btn.textContent = &#39;Copy&#39;, 2000);
        } catch (err) {
            console.error(&#39;Copy failed:&#39;, 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) -&gt; Optional&#91;&#39;Language&#39;&#93;:
    mapping = {
        &#39;.py&#39;: cls.PYTHON,
        &#39;.js&#39;: cls.JAVASCRIPT,
        &#39;.rs&#39;: cls.RUST,
        &#39;.go&#39;: 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(&#39;\n&#39;) + 1
    self.size_bytes = len(self.content.encode(&#39;utf-8&#39;))

@property
def is_large(self) -&gt; bool:
    return self.lines &gt; 100 or self.size_bytes &gt; 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, &#39;r&#39;)
    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&#34;⏱️  {func.__name__} took {elapsed:.3f}s&#34;)
    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) -&gt; Dict&#91;str, str&#93;:
    &#34;&#34;&#34;Cached theme colors&#34;&#34;&#34;
    themes = {
        &#34;dracula&#34;: {
            &#34;background&#34;: &#34;#282a36&#34;,
            &#34;foreground&#34;: &#34;#f8f8f2&#34;,
            &#34;comment&#34;: &#34;#6272a4&#34;,
            &#34;cyan&#34;: &#34;#8be9fd&#34;,
            &#34;green&#34;: &#34;#50fa7b&#34;,
            &#34;orange&#34;: &#34;#ffb86c&#34;,
            &#34;pink&#34;: &#34;#ff79c6&#34;,
            &#34;purple&#34;: &#34;#bd93f9&#34;,
            &#34;red&#34;: &#34;#ff5555&#34;,
            &#34;yellow&#34;: &#34;#f1fa8c&#34;
        }
    }
    return themes.get(self.theme, themes&#91;&#34;dracula&#34;&#93;)

@time_it
async def highlight_file(self, filepath: Path) -&gt; str:
    &#34;&#34;&#34;Async file highlighting&#34;&#34;&#34;
    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&#34;Unsupported file type: {filepath.suffix}&#34;)
    
    code_block = CodeBlock(content, language)
    return await self.process_highlighting(code_block)

async def process_highlighting(self, block: CodeBlock) -&gt; str:
    &#34;&#34;&#34;Process syntax highlighting asynchronously&#34;&#34;&#34;
    # Simulate async processing
    await asyncio.sleep(0.1)
    
    colors = self.get_theme_colors()
    lines = block.content.split(&#39;\n&#39;)
    
    highlighted = &#91;&#93;
    for i, line in enumerate(lines, 1):
        if block.line_numbers:
            line_num = f&#39;&lt;span class=&#34;line-number&#34;&gt;{i:4d}&lt;/span&gt; &#39;
        else:
            line_num = &#39;&#39;
        
        # Simple token highlighting (demonstration)
        line = self._highlight_tokens(line, colors)
        highlighted.append(f&#39;{line_num}{line}&#39;)
    
    return &#39;\n&#39;.join(highlighted)

def _highlight_tokens(self, line: str, colors: Dict&#91;str, str&#93;) -&gt; str:
    &#34;&#34;&#34;Apply syntax highlighting to tokens&#34;&#34;&#34;
    # Python-specific keywords
    keywords = &#91;&#39;def&#39;, &#39;class&#39;, &#39;async&#39;, &#39;await&#39;, &#39;import&#39;, &#39;from&#39;, 
               &#39;if&#39;, &#39;else&#39;, &#39;elif&#39;, &#39;for&#39;, &#39;while&#39;, &#39;return&#39;, 
               &#39;try&#39;, &#39;except&#39;, &#39;finally&#39;, &#39;with&#39;, &#39;as&#39;&#93;
    
    for keyword in keywords:
        line = line.replace(f&#39; {keyword} &#39;, 
                          f&#39; &lt;span style=&#34;color: {colors&#91;&#34;pink&#34;&#93;}&#34;&gt;{keyword}&lt;/span&gt; &#39;)
    
    # Highlight strings (simple version)
    import re
    line = re.sub(r&#39;(&#91;&#34;\&#39;&#93;)(&#91;^&#34;\&#39;&#93;*)\1&#39;, 
                 rf&#39;&lt;span style=&#34;color: {colors&#91;&#34;yellow&#34;&#93;}&#34;&gt;\1\2\1&lt;/span&gt;&#39;, 
                 line)
    
    # Highlight comments
    if &#39;#&#39; in line:
        comment_start = line.index(&#39;#&#39;)
        line = (line&#91;:comment_start&#93; + 
               f&#39;&lt;span style=&#34;color: {colors&#91;&#34;comment&#34;&#93;}&#34;&gt;{line&#91;comment_start:&#93;}&lt;/span&gt;&#39;)
    
    return line

async def batch_highlight(self, files: List&#91;Path&#93;) -&gt; AsyncIterator&#91;str&#93;:
    &#34;&#34;&#34;Yield highlighted files as they complete&#34;&#34;&#34;
    tasks = &#91;self.highlight_file(file) for file in files&#93;
    
    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(&#34;dracula&#34;) as highlighter:
    # Single file
    if files_to_highlight&#91;0&#93;.exists():
        result = await highlighter.highlight_file(files_to_highlight&#91;0&#93;)
        print(f&#34;Highlighted {files_to_highlight&#91;0&#93;.name}&#34;)
    
    # Batch processing
    async for highlighted in highlighter.batch_highlight(files_to_highlight):
        print(f&#34;Processed file with {len(highlighted)} characters&#34;)

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 ~* &#39;^&#91;A-Za-z0-9._%+-&#93;+@&#91;A-Za-z0-9.-&#93;+\.&#91;A-Z|a-z&#93;{2,}$&#39;),
CONSTRAINT username_length CHECK (LENGTH(username) &gt;= 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) &lt; 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 &gt;= CURRENT_DATE - INTERVAL &#39;7 days&#39;
WHERE 
    p.status = &#39;published&#39;
    AND p.published_at &gt;= CURRENT_DATE - INTERVAL &#39;30 days&#39;
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(&#39;day&#39;, created_at)) &gt; 0
    THEN ROUND(
        ((COUNT(*)::NUMERIC - LAG(COUNT(*), 7) OVER (ORDER BY DATE_TRUNC(&#39;day&#39;, created_at))) 
        / LAG(COUNT(*), 7) OVER (ORDER BY DATE_TRUNC(&#39;day&#39;, 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 || &#39;.&#39; || 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 &lt; 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(&#91;${new Date().toISOString()}&#93; Calling ${propertyKey}); try { const result = await original.apply(this, args); console.log(&#91;${new Date().toISOString()}&#93; Success: ${propertyKey}); return result; } catch (error) { console.error(&#91;${new Date().toISOString()}&#93; 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}&amp;size=${pageSize} ); const data = await response.json();

yield data.items as T&#91;&#93;;

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&lt;T&gt;(resolve =&gt; {
  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.