Skip to content

Commit 58fd672

Browse files
feat: added dag iteration function
1 parent 959dd7e commit 58fd672

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

dag/dag.go

+39
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ import (
77
"log"
88
"os"
99
"path/filepath"
10+
"sort"
1011
"strconv"
12+
"strings"
1113

1214
cbor "github.com/fxamacker/cbor/v2"
1315
"github.com/multiformats/go-multibase"
@@ -357,3 +359,40 @@ func (dag *Dag) GetDataFromLeaf(leaf *DagLeaf) ([]byte, error) {
357359

358360
return content, nil
359361
}
362+
363+
func (d *Dag) IterateDag(processLeaf func(leaf *DagLeaf, parent *DagLeaf)) error {
364+
var iterate func(leafHash string, parentHash *string) error
365+
iterate = func(leafHash string, parentHash *string) error {
366+
leaf, exists := d.Leafs[leafHash]
367+
if !exists {
368+
return fmt.Errorf("child is missing when iterating dag")
369+
}
370+
371+
var parent *DagLeaf
372+
if parentHash != nil {
373+
parent = d.Leafs[*parentHash]
374+
}
375+
376+
processLeaf(leaf, parent)
377+
378+
childHashes := []string{}
379+
for _, childHash := range leaf.Links {
380+
childHashes = append(childHashes, childHash)
381+
}
382+
383+
sort.Slice(childHashes, func(i, j int) bool {
384+
numI, _ := strconv.Atoi(strings.Split(childHashes[i], ":")[0])
385+
numJ, _ := strconv.Atoi(strings.Split(childHashes[j], ":")[0])
386+
387+
return numI < numJ
388+
})
389+
390+
for _, childHash := range childHashes {
391+
return iterate(childHash, &leaf.Hash)
392+
}
393+
394+
return nil
395+
}
396+
397+
return iterate(d.Root, nil)
398+
}

0 commit comments

Comments
 (0)