@@ -3,6 +3,7 @@ import { BIDSFile, FileOpener, FileTree } from '../types/filetree.ts'
33import type { DatasetIssues } from '../issues/datasetIssues.ts'
44import { loadTSV } from '../files/tsv.ts'
55import { loadJSON } from '../files/json.ts'
6+ import { queuedAsyncIterator } from '../utils/queue.ts'
67
78function * quickWalk ( dir : FileTree ) : Generator < BIDSFile > {
89 for ( const file of dir . files ) {
@@ -38,11 +39,13 @@ function pseudoFile(dir: FileTree, opaque: boolean): BIDSFile {
3839 )
3940}
4041
42+ type CleanupFunction = ( ) => void
43+
4144/** Recursive algorithm for visiting each file in the dataset, creating a context */
4245async function * _walkFileTree (
4346 fileTree : FileTree ,
4447 dsContext : BIDSContextDataset ,
45- ) : AsyncIterable < BIDSContext > {
48+ ) : AsyncIterable < BIDSContext | CleanupFunction > {
4649 for ( const file of fileTree . files ) {
4750 yield new BIDSContext ( file , dsContext )
4851 }
@@ -56,13 +59,23 @@ async function* _walkFileTree(
5659 yield * _walkFileTree ( dir , dsContext )
5760 }
5861 }
59- loadTSV . cache . delete ( fileTree . path )
60- loadJSON . cache . delete ( fileTree . path )
62+ yield ( ) => {
63+ loadTSV . cache . delete ( fileTree . path )
64+ loadJSON . cache . delete ( fileTree . path )
65+ }
6166}
6267
6368/** Walk all files in the dataset and construct a context for each one */
6469export async function * walkFileTree (
6570 dsContext : BIDSContextDataset ,
71+ bufferSize : number = 1 ,
6672) : AsyncIterable < BIDSContext > {
67- yield * _walkFileTree ( dsContext . tree , dsContext )
73+ for await (
74+ await using context of queuedAsyncIterator (
75+ _walkFileTree ( dsContext . tree , dsContext ) ,
76+ bufferSize ,
77+ )
78+ ) {
79+ yield context
80+ }
6881}
0 commit comments