Skill站外收录 @skilllib/skill-2117939930272411966
single-or-array-pattern
提供一种统一处理单个对象或对象数组的函数设计模式,通过运行时类型判断自动归一化输入为数组形式,再交由内部纯数组逻辑处理,兼顾调用便捷性与实现一致性,适用于增删改查、批量操作及工厂类接口。
软件开发 AI 技能
Skills.MD
# Single-or-Array Overload Pattern
Accept both single items and arrays, normalize internally, delegate to array-only implementation.
## Quick Reference
```typescript
// Option 1: Explicit overloads (cleaner IDE signatures)
function create(item: T): Promise<Result<T, E>>;
function create(items: T[]): Promise<Result<T[], E>>;
function create(itemOrItems: T | T[]): Promise<Result<T | T[], E>> {
const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];
return createInternal(items);
}
// Option 2: Union type (less boilerplate)
function create(itemOrItems: T | T[]): Promise<Result<void, E>> {
const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];
// ... implementation
}
```
## The Structure
1. **Public API**: Accepts `T | T[]`
2. **Normalization**: `Array.isArray()` check, wrap single in array
3. **Internal function**: Only handles arrays
```typescript
// Public: flexible API
function createServer(clientOrClients: Client | Client[], options?: Options) {
const clients = Array.isArray(clientOrClients)
? clientOrClients
: [clientOrClients];
return createServerInternal(clients, options);
}
// Internal: array-only, all real logic here
function createServerInternal(clients: Client[], options?: Options) {
// Implementation only handles arrays
}
```
## Naming Conventions
| Parameter | Normalized Variable |
| ----------------------- | ------------------- |
| `recordingOrRecordings` | `recordings` |
| `clientOrClients` | `clients` |
| `itemOrItems` | `items` |
| `paramsOrParamsArray` | `paramsArray` |
## When to Use
**Good fit:**
- CRUD operations (create, update, delete)
- Batch processing APIs
- Factory functions accepting dependencies
- Any "do this to one or many" scenario
**Skip when:**
- Single vs batch have different semantics
- Return types vary significantly
- Array version needs different options
## Codebase Examples
### Server Factory (`packages/epicenter/src/server/server.ts`)
```typescript
function createServer(
client: AnyWorkspaceClient,
options?: ServerOptions,
): ReturnType<typeof createServerInternal>;
function createServer(
clients: AnyWorkspaceClient[],
options?: ServerOptions,
): ReturnType<typeof createServerInternal>;
function createServer(
clientOrClients: AnyWorkspaceClient | AnyWorkspaceClient[],
options?: ServerOptions,
) {
const clients = Array.isArray(clientOrClients)
? clientOrClients
: [clientOrClients];
return createServerInternal(clients, options);
}
```
### Database Service (`apps/whispering/src/lib/services/isomorphic/db/web.ts`)
```typescript
delete: async (recordingOrRecordings) => {
const recordings = Array.isArray(recordingOrRecordings)
? recordingOrRecordings
: [recordingOrRecordings];
const ids = recordings.map((r) => r.id);
return tryAsync({
try: () => db.recordings.bulkDelete(ids),
catch: (error) => DbServiceErr({ message: `Error deleting: ${error}` }),
});
},
```
### Query Mutations (`apps/whispering/src/lib/query/isomorphic/db.ts`)
```typescript
delete: defineMutation({
mutationFn: async (recordings: Recording | Recording[]) => {
const recordingsArray = Array.isArray(recordings)
? recordings
: [recordings];
for (const recording of recordingsArray) {
services.db.recordings.revokeAudioUrl(recording.id);
}
const { error } = await services.db.recordings.delete(recordingsArray);
if (error) return Err(error);
return Ok(undefined);
},
}),
```
## Anti-Patterns
### Don't: Separate functions for single vs array
```typescript
// Harder to maintain, users must remember two APIs
function createRecording(recording: Recording): Promise<...>;
function createRecordings(recordings: Recording[]): Promise<...>;
```
### Don't: Force arrays everywhere
```typescript
// Awkward for single items
createRecordings([recording]); // Ugly
```
### Don't: Duplicate logic in overloads
```typescript
// BAD: Logic duplicated
function create(item: T) {
return db.insert(item); // Duplicated
}
function create(items: T[]) {
return db.bulkInsert(items); // Different code path
}
// GOOD: Single implementation
function create(itemOrItems: T | T[]) {
const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];
return db.bulkInsert(items); // One code path
}
```
## References
- [Full article](../../docs/articles/single-or-array-overload-pattern.md) — detailed explanation with more examples
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「single-or-array-pattern」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次