常用代码段展示
页面中的代码主要用于整理日常开发中常见的写法、工具函数和练习示例,方便按主题快速查阅。
JavaScript / 格式化时间
function formatDate(date) {
const d = new Date(date);
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
return `${y}-${m}-${day}`;
}
Python / 读取文本文件
from pathlib import Path
file_path = Path("notes.txt")
content = file_path.read_text(encoding="utf-8")
print(content)
CSS / 卡片悬停效果
.card {
transition: transform 0.25s ease, box-shadow 0.25s ease;
}
.card:hover {
transform: translateY(-4px);
box-shadow: 0 14px 24px rgba(0, 0, 0, 0.12);
}
Java / 列表转映射
public static Map<Long, User> toUserMap(List<User> users) {
return users.stream()
.collect(Collectors.toMap(
User::getId,
item -> item,
(left, right) -> left,
LinkedHashMap::new
));
}
Java / 简单结果封装
public class Result<T> {
private final boolean success;
private final String message;
private final T data;
private Result(boolean success, String message, T data) {
this.success = success;
this.message = message;
this.data = data;
}
public static <T> Result<T> ok(T data) {
return new Result<>(true, "success", data);
}
}
HTML / 基础信息卡片
<section class="profile-card">
<h3>学习主题</h3>
<p>记录近期整理过的代码片段与注意事项。</p>
<a href="#snippets">查看摘录</a>
</section>
Java / Stream 分组统计
public Map<String, Long> countSuccessByType(List<OrderLog> logs) {
return logs.stream()
.filter(Objects::nonNull)
.filter(log -> log.getType() != null)
.collect(Collectors.groupingBy(
OrderLog::getType,
LinkedHashMap::new,
Collectors.filtering(
log -> Boolean.TRUE.equals(log.getSuccess()),
Collectors.counting()
)
));
}
Java / 异步批量查询
public CompletableFuture<Map<Long, UserProfile>> loadProfilesAsync(
List<Long> userIds, Executor executor) {
List<CompletableFuture<UserProfile>> tasks = userIds.stream()
.distinct()
.map(id -> CompletableFuture.supplyAsync(() -> profileService.load(id), executor))
.toList();
return CompletableFuture.allOf(tasks.toArray(CompletableFuture[]::new))
.thenApply(ignored -> tasks.stream()
.map(CompletableFuture::join)
.filter(Objects::nonNull)
.collect(Collectors.toMap(
UserProfile::getUserId,
profile -> profile,
(left, right) -> right
)));
}
JavaScript / 请求重试封装
async function requestWithRetry(requestFn, retries = 3, delay = 500) {
let lastError;
for (let index = 0; index < retries; index += 1) {
try {
return await requestFn();
} catch (error) {
lastError = error;
if (index === retries - 1) {
break;
}
await new Promise(resolve => setTimeout(resolve, delay * (index + 1)));
}
}
throw lastError;
}
Python / 递归扫描并汇总
from collections import Counter
from pathlib import Path
def count_suffixes(root: Path) -> Counter:
counter = Counter()
for path in root.rglob("*"):
if path.is_file():
suffix = path.suffix.lower() or "[no_ext]"
counter[suffix] += 1
return Counter(dict(sorted(counter.items(), key=lambda item: item[1], reverse=True)))
SQL / 按月统计活跃用户
SELECT
DATE_FORMAT(login_time, '%Y-%m') AS login_month,
COUNT(DISTINCT user_id) AS active_users,
COUNT(*) AS total_logins
FROM user_login_log
WHERE login_time >= '2026-01-01 00:00:00'
AND status = 'SUCCESS'
GROUP BY DATE_FORMAT(login_time, '%Y-%m')
ORDER BY login_month DESC;