All files / src/codec/edges decode.ts

100% Statements 21/21
100% Branches 3/3
100% Functions 3/3
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 341x 1x 1x 1x 1x                 1x 1431x 1431x 1431x 1431x 1431x 1431x 1431x 1431x 1431x     1x 375x     1x 1x 1x 1x  
import {type Branch, treeAna, type TreeUnfolderK} from '#tree'
import * as TreeF from '#treeF'
import {Array, flow, pipe} from 'effect'
import {indexParents} from './map.js'
import {getMapChildren, setMapRoot} from './ops.js'
import type {EdgeList, EdgeMap, EdgeMapTypeLambda} from './types.js'
 
/**
 * Decode a level of a tree encoded as an edge list.
 * @category codec
 * @category unfold
 * @function
 */
export const decodeUnfold: TreeUnfolderK<EdgeMapTypeLambda> = map => {
  const [root, children] = getMapChildren(map)
  return pipe(
    children,
    Array.match({
      onEmpty: () => TreeF.leafF(root),
      onNonEmpty: flow(Array.map(setMapRoot(map)), TreeF.treeF.flipped(root)),
    }),
  )
}
 
/** Decode an edge map into a tree. */
export const decodeMap = <A>(map: EdgeMap<A>) =>
  pipe(map, treeAna(decodeUnfold)) as Branch<A>
 
/** Decode an edge list into a tree. */
export const decode: <A>(edges: EdgeList<A>) => Branch<A> = flow(
  indexParents,
  decodeMap,
)