refactor: satisfy no-array-filter-map and no-accumulating-spread

This commit is contained in:
Chris Scott committed 2026-11-13 01:45:13 -05:00
1 parent b96a248cef
commit 19ee1d9173
16 files changed
+68 -68

No files matched your search

@@ -18,9 +18,7 @@ function firstExistingConfigSourcePath(): string | null {
const candidates = [
process.env.OPENCODE_IMPORT_CONFIG_PATH,
path.join(os.homedir(), '.config', 'opencode', 'opencode.json'),
]
.filter((value): value is string => Boolean(value))
.map((value) => path.resolve(value))
].flatMap((value) => (value ? [path.resolve(value)] : []))
return Array.from(new Set(candidates)).find((candidate) => existsSync(candidate)) ?? null
}
+5 -6
View File
@@ -77,9 +77,7 @@ export interface ImportedSessionDirectorySummary {
}
export function getImportPathCandidates(envKey: string, fallbackPath: string): string[] {
const candidates = [process.env[envKey], fallbackPath]
.filter((value): value is string => Boolean(value))
.map((value) => path.resolve(value))
const candidates = [process.env[envKey], fallbackPath].flatMap((value) => (value ? [path.resolve(value)] : []))
return Array.from(new Set(candidates))
}
@@ -89,9 +87,10 @@ function getExistingConfigSourcePaths(): string[] {
if (explicitPath && existsSync(path.resolve(explicitPath))) {
return [path.resolve(explicitPath)]
}
return [...OPENCODE_CONFIG_SOURCE_NAMES, LEGACY_OPENCODE_CONFIG_SOURCE_NAME]
.map(name => path.join(os.homedir(), '.config', 'opencode', name))
.filter(candidate => existsSync(candidate))
return [...OPENCODE_CONFIG_SOURCE_NAMES, LEGACY_OPENCODE_CONFIG_SOURCE_NAME].flatMap(name => {
const candidate = path.join(os.homedir(), '.config', 'opencode', name)
return existsSync(candidate) ? [candidate] : []
})
}
async function getFirstExistingPathWithDatabase(paths: string[]): Promise<string | null> {
+7 -6
View File
@@ -993,9 +993,10 @@ async function admitVmStart(name: string, maxRunningVms: number): Promise<void>
if (running.length < maxRunningVms) return
const execTimeoutMs = ENV.SANDBOX.EXEC_TIMEOUT_MS
const candidates = running
.map((vmName) => ({ vmName, lastUsedAt: vmStates.get(vmName)?.lastUsedAt ?? 0 }))
.filter((candidate) => Date.now() - candidate.lastUsedAt >= execTimeoutMs)
const candidates = running.flatMap((vmName) => {
const lastUsedAt = vmStates.get(vmName)?.lastUsedAt ?? 0
return Date.now() - lastUsedAt >= execTimeoutMs ? [{ vmName, lastUsedAt }] : []
})
if (candidates.length === 0) {
throw new Error(
`${running.length} sandbox VMs are already running (the limit in Settings → Sandbox is ${maxRunningVms}) and none has been idle for ${execTimeoutMs / 60000} minutes; retry when a sandboxed command finishes or raise the limit`,
@@ -1196,9 +1197,9 @@ export class SandboxRuntimeService {
private async runManagedSandboxStop(): Promise<void> {
for (;;) {
const inFlight = [...vmStates.values()]
.map((state) => state.inFlightBoot)
.filter((boot): boot is Promise<void> => boot !== null)
const inFlight: Promise<void>[] = [...vmStates.values()].flatMap((state) =>
state.inFlightBoot === null ? [] : [state.inFlightBoot],
)
if (inFlight.length === 0) break
await Promise.all(inFlight.map((boot) => boot.catch(() => undefined)))
}
+8 -6
View File
@@ -201,12 +201,14 @@ export class ScheduleWorktreeManager {
): Promise<void> {
const sharedPath = getScheduleWorktreePath(job.id, null)
const sharedBranch = getScheduleWorktreeBranch(job.id, null)
const runWorktrees = artifacts
.map((artifact) => artifact.worktreePath)
.filter((worktreePath): worktreePath is string => worktreePath !== null && worktreePath !== sharedPath)
const branches = artifacts
.map((artifact) => artifact.runBranch)
.filter((branch): branch is string => branch !== null && branch.length > 0 && branch !== sharedBranch)
const runWorktrees = artifacts.flatMap((artifact) => {
const worktreePath = artifact.worktreePath
return worktreePath !== null && worktreePath !== sharedPath ? [worktreePath] : []
})
const branches = artifacts.flatMap((artifact) => {
const branch = artifact.runBranch
return branch !== null && branch.length > 0 && branch !== sharedBranch ? [branch] : []
})
if (runWorktrees.length === 0 && branches.length === 0) return
+5 -4
View File
@@ -99,12 +99,13 @@ function prepareSingleSkillFiles(files: SkillInstallFile[]): PreparedSkillFiles
const skillDir = path.dirname(skillMd.relativePath)
const { name, description, body } = parseSkillMarkdown(skillMd.content.toString('utf-8'))
const prefix = skillDir === '.' ? '' : skillDir + '/'
const strippedFiles = normalized
.filter(f => f.relativePath === skillMd.relativePath || f.relativePath.startsWith(prefix))
.map(f => ({
const strippedFiles = normalized.flatMap(f => {
if (f.relativePath !== skillMd.relativePath && !f.relativePath.startsWith(prefix)) return []
return [{
...f,
relativePath: skillDir === '.' ? f.relativePath : f.relativePath.substring(prefix.length),
}))
}]
})
for (const f of strippedFiles) {
const checkPath = normalizeUploadRelativePath(f.relativePath)
if (checkPath.startsWith('..')) {
@@ -441,18 +441,17 @@ function buildGroupEntries(
})
})
const groups = worktrees
.filter((worktree) => ownerFilter === 'all' || worktree.worktreeSource === ownerFilter)
.map((worktree): WorktreeGroup => {
const groupSessions = sessionsByDirectory.get(worktree.fullPath) ?? []
return {
worktree,
directory: worktree.fullPath,
sessions: groupSessions,
lastActive: groupSessions[0]?.time.updated ?? 0,
}
})
.filter((group) => !hideEmpty || group.sessions.length > 0)
const groups = worktrees.flatMap((worktree): WorktreeGroup[] => {
if (ownerFilter !== 'all' && worktree.worktreeSource !== ownerFilter) return []
const groupSessions = sessionsByDirectory.get(worktree.fullPath) ?? []
const group: WorktreeGroup = {
worktree,
directory: worktree.fullPath,
sessions: groupSessions,
lastActive: groupSessions[0]?.time.updated ?? 0,
}
return !hideEmpty || groupSessions.length > 0 ? [group] : []
})
const scheduleEntries = new Map<number, Extract<GroupEntry, { kind: 'schedule' }>>()
const multiRunEntries = new Map<number, Extract<GroupEntry, { kind: 'multiRun' }>>()
@@ -145,7 +145,7 @@ function expandDayOfWeekExpression(expression: string): string[] | null {
return null
}
return weekdayOptions.filter((option) => days.has(option.value)).map((option) => option.value)
return weekdayOptions.flatMap((option) => (days.has(option.value) ? [option.value] : []))
}
function sortWeekdayValues(values: string[]): string[] {
@@ -27,9 +27,11 @@ interface KeyValueEntry {
function toRecord(entries: KeyValueEntry[]): Record<string, string> | undefined {
const record = Object.fromEntries(
entries
.filter((entry) => entry.key.trim() && entry.value.trim())
.map((entry) => [entry.key.trim(), entry.value.trim()]),
entries.flatMap((entry): [string, string][] => {
const key = entry.key.trim()
const value = entry.value.trim()
return key && value ? [[key, value]] : []
}),
)
return Object.keys(record).length > 0 ? record : undefined
}
+7 -7
View File
@@ -99,13 +99,13 @@ function usePendingSessionIDs(bySession: Record<string, unknown[]>): string[] {
}
function groupBySession<T extends SessionScopedItem>(items: T[]): Record<string, T[]> {
return items.reduce<Record<string, T[]>>((grouped, item) => {
const existing = grouped[item.sessionID] ?? []
return {
...grouped,
[item.sessionID]: [...existing, item],
}
}, {})
const groups = new Map<string, T[]>()
for (const item of items) {
const existing = groups.get(item.sessionID)
if (existing) existing.push(item)
else groups.set(item.sessionID, [item])
}
return Object.fromEntries(groups)
}
function sortById<T extends SessionScopedItem>(items: T[]): T[] {
+8 -10
View File
@@ -96,16 +96,14 @@ export function buildModelSections(
function uniqueModelSections(sections: ModelSection[]): ModelSection[] {
const seen = new Set<string>()
return sections
.map((section) => ({
...section,
options: section.options.filter((option) => {
if (seen.has(option.value)) return false
seen.add(option.value)
return true
}),
}))
.filter((section) => section.options.length > 0)
return sections.flatMap((section): ModelSection[] => {
const options = section.options.filter((option) => {
if (seen.has(option.value)) return false
seen.add(option.value)
return true
})
return options.length > 0 ? [{ ...section, options }] : []
})
}
function compareSearchMatches(a: ModelOption, b: ModelOption): number {
+1 -1
View File
@@ -13,7 +13,7 @@ export function getRepoBranchLabel(repo: Pick<Repo, 'currentBranch' | 'branch'>)
const ORIGIN_REMOTE_PREFIX = 'remotes/origin/'
export function getOriginOnlyBranchNames(branches: Pick<GitBranch, 'name' | 'type'>[]): string[] {
const localNames = new Set(branches.filter((b) => b.type === 'local').map((b) => b.name))
const localNames = new Set(branches.flatMap((b) => (b.type === 'local' ? [b.name] : [])))
const seen = new Set<string>()
const result: string[] = []
+3 -3
View File
@@ -8,9 +8,9 @@ export function collectVisibleAssistantTexts(
): string[] {
const containerRect = container.getBoundingClientRect()
const textById = new Map(
messages
.filter((message) => message.type === 'assistant')
.map((message) => [message.id, getAssistantText(message).trim()]),
messages.flatMap((message): [string, string][] =>
message.type === 'assistant' ? [[message.id, getAssistantText(message).trim()]] : [],
),
)
return Array.from(container.querySelectorAll<HTMLElement>('[data-message-id]'))
.filter((element) => {
+3 -3
View File
@@ -100,7 +100,7 @@ function applyRevertBoundary(
}
async function fetchCompleteSessionHistory(sessionID: string, serverId?: string): Promise<SessionMessageInfo[]> {
let history: SessionMessageInfo[] = []
const pagesNewestFirst: SessionMessageInfo[][] = []
const seenIds = new Set<string>()
const seenCursors = new Set<string>()
let cursor: string | undefined
@@ -109,9 +109,9 @@ async function fetchCompleteSessionHistory(sessionID: string, serverId?: string)
const page = await listSessionMessages(sessionID, cursor === undefined ? {} : { cursor }, serverId)
const older = page.messages.filter((message) => !seenIds.has(message.id))
for (const message of older) seenIds.add(message.id)
history = [...older, ...history]
pagesNewestFirst.push(older)
if (!page.nextCursor || seenCursors.has(page.nextCursor)) return history
if (!page.nextCursor || seenCursors.has(page.nextCursor)) return pagesNewestFirst.reverse().flat()
seenCursors.add(page.nextCursor)
cursor = page.nextCursor
}
+1 -1
View File
@@ -533,7 +533,7 @@ export function installResizeObserver(): ResizeObserverFake {
vi.stubGlobal('ResizeObserver', FakeResizeObserver)
return {
observedElements: () => observations.filter((entry) => entry.element.isConnected).map((entry) => entry.element),
observedElements: () => observations.flatMap((entry) => (entry.element.isConnected ? [entry.element] : [])),
reportHeight: (height) => {
act(() => {
for (const entry of [...observations]) {
+1 -1
View File
@@ -114,7 +114,7 @@ async function chooseFromLocal(
const matchIds = new Set(matches.map((repo) => repo.repoId))
return selectDialog<SwitchChoice>(context, 'Switch to Manager repo', [
...matches.map((repo) => repoOption(repo, MATCH_CATEGORY)),
...repos.filter((repo) => !matchIds.has(repo.repoId)).map((repo) => repoOption(repo, REPO_CATEGORY)),
...repos.flatMap((repo) => (matchIds.has(repo.repoId) ? [] : [repoOption(repo, REPO_CATEGORY)])),
])
}
+1 -1
View File
@@ -1216,7 +1216,7 @@ describe('mirrorUpFast targets the selected repo', () => {
await mirrorUpFast(plan, { api, force: false, onPhase: (p) => phases.push(p) })
expect(phases.map((p) => p.kind)).toEqual(['bundling', 'uploading', 'uploading', 'uploading', 'processing', 'patching'])
const sent = phases.filter((p): p is Extract<MirrorUpFastPhase, { kind: 'uploading' }> => p.kind === 'uploading').map((p) => p.bytesSent)
const sent = phases.flatMap((p): number[] => (p.kind === 'uploading' ? [p.bytesSent] : []))
expect(sent[0]).toBe(0)
expect(sent[1]!).toBeGreaterThan(0)
expect(sent[2]!).toBeGreaterThan(sent[1]!)