Pattern for functions that accept either a single item or an array. Use when creating CRUD operations, batch processing APIs, or factory functions that should flexibly handle one or many inputs.
Accept both single items and arrays, normalize at the top, process uniformly.
function create(itemOrItems: T | T[]): Promise<Result<void, E>> {
const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];
// ... implementation works on items array
}
T | T[] as the parameter typeArray.isArray() at the top of the functionfunction createServer(clientOrClients: Client | Client[], options?: Options) {
const clients = Array.isArray(clientOrClients)
? clientOrClients
: [clientOrClients];
// All real logic here, working with the array
for (const client of clients) {
// ...
}
}
| Parameter | Normalized Variable |
|---|---|
recordingOrRecordings | recordings |
clientOrClients | clients |
itemOrItems | items |
paramsOrParamsArray | paramsArray |
Good fit:
Skip when:
packages/server/src/server.ts)function createServer(
clientOrClients: AnyWorkspaceClient | AnyWorkspaceClient[],
options?: ServerOptions,
) {
const clients = Array.isArray(clientOrClients)
? clientOrClients
: [clientOrClients];
// All server setup logic directly here
const workspaces: Record<string, AnyWorkspaceClient> = {};
for (const client of clients) {
workspaces[client.id] = client;
}
// ...
}
apps/whispering/src/lib/services/isomorphic/db/web.ts)