Files
darkwave/posts/code-syntax.md

192 lines
3.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: "Пример кода с подсветкой"
date: "2026-01-20"
tags: ["code", "syntax", "programming"]
---
# Примеры кода с подсветкой синтаксиса
## JavaScript
```javascript
// Комментарий
const hello = (name) => {
console.log(`Hello, ${name}!`);
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
return doubled;
};
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi, I'm ${this.name}`;
}
}
```
## Python
```python
def fibonacci(n):
"""Вычисляет числа Фибоначчи"""
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
# Генератор списка
squares = [x**2 for x in range(10)]
# Декоратор
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Время выполнения: {end - start} секунд")
return result
return wrapper
```
## RISC-V Ассемблер
```asm
# Простой цикл на RISC-V
loop:
addi t0, t0, 1 # t0 = t0 + 1
addi t1, t1, -1 # t1 = t1 - 1
bnez t1, loop # if t1 != 0, goto loop
# Функция сложения
add_numbers:
add a0, a0, a1 # a0 = a0 + a1
ret # return
```
## CSS
```css
/* Кастомные свойства */
:root {
--primary-color: #3b82f6;
--secondary-color: #10b981;
--text-color: #374151;
}
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1rem;
padding: 2rem;
}
.button {
background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
color: white;
padding: 0.75rem 1.5rem;
border-radius: 0.5rem;
transition: transform 0.2s;
}
.button:hover {
transform: translateY(-2px);
}
```
## Bash/Shell
```bash
#!/bin/bash
# Скрипт для сборки проекта
echo "Начало сборки..."
# Проверка зависимостей
if ! command -v npm &> /dev/null; then
echo "Ошибка: npm не установлен"
exit 1
fi
# Установка зависимостей
npm install
# Сборка проекта
npm run build
echo "Сборка завершена успешно!"
```
## SQL
```sql
-- Создание таблицы пользователей
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT TRUE
);
-- Запрос с JOIN
SELECT
u.username,
o.order_id,
o.total_amount,
o.order_date
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.is_active = TRUE
ORDER BY o.order_date DESC;
```
## C++
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
// Шаблонная функция
template<typename T>
T find_max(const std::vector<T>& vec) {
if (vec.empty()) {
throw std::invalid_argument("Vector is empty");
}
return *std::max_element(vec.begin(), vec.end());
}
// Класс для работы с матрицами
class Matrix {
private:
std::vector<std::vector<double>> data;
int rows, cols;
public:
Matrix(int r, int c) : rows(r), cols(c) {
data.resize(r, std::vector<double>(c, 0.0));
}
// Перегрузка оператора
Matrix operator+(const Matrix& other) const {
Matrix result(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.data[i][j] = data[i][j] + other.data[i][j];
}
}
return result;
}
};
```