All files / src/tree data.ts

100% Statements 132/132
100% Branches 45/45
100% Functions 24/24
100% Lines 132/132

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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 4111x 1x 1x 1x 1x                                                     1x 1x 1x 1x                                       1x 44x 44x 44x 44x 44x 44x 44x                                       1x 13929x 13929x 13929x 13929x 13929x 13929x 13929x                                       1x 2x 2x                                   1x     1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x   1x 18x                                     1x       1x 1x 1x 1x 1x 1x                                               1x     1x 1x 1x 4x 1x                       1x     1x 1x 1x 1x 1x                           1x     1x 1x 1x 17x 1x                     1x 1x   12x 12x                               1x 2x                               1x 2x   1x 21x 21x 21x 21x 21x 16x 21x 21x                               1x       1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 12x 12x   11x 12x   7x 7x 7x 7x   5x 5x                                   1x       1x 1x 1x 1x 1x 1x   1x 3x 3x 3x 3x 3x 3x 3x                           1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import {dual, type EndoOf} from '#Function'
import {branchF, leafF} from '#treeF'
import {Array, flow, Function, K, Pair, pipe} from '#util'
import {isNone, none, type Option} from 'effect/Option'
import {
  fixBranch,
  getBranchForest,
  getValue,
  isLeaf,
  match,
  tree,
} from './index.js'
import type {Branch, ForestOf, Tree} from './types.js'
 
/**
 * Return direct child count for root node of given tree.
 *
 * See {@link nodeCount} for a version that count _all_ nodes and not just
 * direct children.
 * @example
 * import * as Tree from 'effect-tree'
 *
 * const tree = Tree.tree(1, [Tree.leaf(2), Tree.leaf(3)])
 *
 * expect(Tree.length(tree)).toBe(2)
 * @typeParam A Underlying tree type.
 * @param self The tree being queried.
 * @returns Numeric child count.
 * @category basic
 * @function
 */
export const length: <A>(self: Tree<A>) => number = match({
  onLeaf: () => 0,
  onBranch: (_, forest) => forest.length,
})
 
/**
 * Get the forest of any tree node. Result could be an empty list if the given
 * node is a {@link Leaf}.
 *
 * See {@link getBranchForest} for a version that returns the non-empty forest
 * of a branch.
 * @example
 * import * as Tree from 'effect-tree'
 *
 * const tree = Tree.tree(1, [Tree.leaf(2), Tree.leaf(3)])
 *
 * expect(Tree.getForest(tree)).toEqual([Tree.leaf(2), Tree.leaf(3)])
 * @typeParam A Underlying tree type.
 * @param self The tree being queried.
 * @returns A possibly empty list of trees.
 * @category basic
 * @function
 */
export const getForest = <A>(self: Tree<A>): readonly Tree<A>[] =>
  pipe(
    self,
    match<A, readonly Tree<A>[]>({
      onLeaf: () => [],
      onBranch: (_, forest) => forest,
    }),
  )
 
/**
 * Deconstruct the node and possibly empty forest of a tree. Useful in
 * pipelines.
 * @example
 * import * as Tree from 'effect-tree'
 *
 * const tree = Tree.tree(1, [Tree.leaf(2), Tree.leaf(3)])
 *
 * const [value, forest] = Tree.destruct(tree)
 *
 * expect(value, 'value').toBe(1)
 * expect(forest, 'forest').toEqual([Tree.leaf(2), Tree.leaf(3)])
 * @typeParam A Underlying tree type.
 * @param self The tree being deconstructed.
 * @returns A pair of the tree node value and a possibly empty list of child trees.
 * @category basic
 * @function
 */
export const destruct = <A>(self: Tree<A>): readonly [A, readonly Tree<A>[]] =>
  pipe(
    self,
    match<A, readonly [A, readonly Tree<A>[]]>({
      onLeaf: Pair.pair.withSecond([]),
      onBranch: Pair.pair,
    }),
  )
 
/**
 * Same as {@link destruct} but only for _branches_, so you are guaranteed a
 * non-empty forest.
 * @example
 * import * as Tree from 'effect-tree'
 *
 * const branch: Tree.Branch<number> = Tree.branch(1, [Tree.of(2), Tree.of(3)])
 *
 * const [value, forest] = Tree.destructBranch(branch)
 *
 * expect(value, 'value').toBe(1)
 * expect(forest, 'forest').toEqual([Tree.of(2), Tree.of(3)])
 * @typeParam A Underlying tree type.
 * @param self The branch being deconstructed.
 * @returns A pair of the tree node value and a non-empty list of child trees.
 * @category basic
 * @function
 */
export const destructBranch = <A>({
  unfixed: {node, forest},
}: Branch<A>): [A, Array.NonEmptyReadonlyArray<Tree<A>>] => [node, forest]
 
/**
 * Set the value of a tree root to a given value of the same type.
 * @example
 * import * as Tree from 'effect-tree'
 *
 * const leaf = Tree.of(1)
 * const changed = Tree.setValue(leaf, 2)
 *
 * expect(Tree.getValue(changed)).toBe(2)
 * @typeParam A Underlying tree type.
 * @param self The tree being changed.
 * @param value New value for the root node.
 * @returns A new tree where the root value has been replaced by the given value.
 * @category basic
 * @function
 */
export const setValue: {
  <A>(self: Tree<A>, value: A): Tree<A>
  <A>(value: A): (self: Tree<A>) => Tree<A>
} = dual(
  2,
  <A>(self: Tree<A>, value: A): Tree<A> => ({
    unfixed: pipe(
      self,
      match({
        onLeaf: () => leafF(value),
        onBranch: (_, forest) => branchF(value, forest),
      }),
    ),
  }),
)
 
const _setForest = <A>(self: Tree<A>, forest: ForestOf<A>): Branch<A> =>
  pipe(self, getValue, branchF(forest), fixBranch)
 
/**
 * Set the root node forest to a given forest of the same type. If the given
 * tree is leaf it is upgraded into a branch.
 * @example
 * import * as Tree from 'effect-tree'
 *
 * const leaf = Tree.of(1)
 * const changed = Tree.setForest(leaf, [Tree.of(2)])
 *
 * expect(Tree.getForest(changed)).toEqual([Tree.of(2)])
 * @typeParam A Underlying tree type.
 * @param self The tree being changed.
 * @param forest New forest.
 * @returns A new tree where the forest has been replaced by the given forest.
 * @category basic
 * @function
 */
export const setForest: {
  <A>(self: Tree<A>, forest: ForestOf<A>): Branch<A>
  <A>(forest: ForestOf<A>): (self: Tree<A>) => Branch<A>
  flip: <A>(self: Tree<A>) => (forest: ForestOf<A>) => Branch<A>
} = Object.assign(dual(2, _setForest), {
  flip:
    <A>(self: Tree<A>) =>
    (forest: ForestOf<A>) =>
      _setForest(self, forest),
})
 
/**
 * Run the given function over the given tree if it is a branch, else return the
 * tree unchanged. This is like {@link match} where the `onLeaf` branch is set
 * to `identity`.
 * @example
 * import * as Tree from 'effect-tree'
 *
 * const leaf = Tree.of(1)
 * const branch = Tree.from(2, leaf)
 *
 * const changeBranch = Tree.modBranch(Tree.setValue(3))
 *
 * expect(changeBranch(leaf), 'leaf').toEqual(leaf)
 * expect(changeBranch(branch), 'branch').toEqual(Tree.from(3, leaf))
 * @typeParam A Underlying tree type.
 * @param self Tree on which to run the given function.
 * @param f A function from {@link Branch} to {@link Tree}.
 * @returns The tree unchanged if it is a leaf, else the result of applying the
 * given function on the branch.
 * @category basic
 * @function
 */
export const modBranch: {
  <A>(self: Tree<A>, f: (branch: Branch<A>) => Tree<A>): Tree<A>
  <A>(f: (branch: Branch<A>) => Tree<A>): (self: Tree<A>) => Tree<A>
} = dual(
  2,
  <A>(self: Tree<A>, f: (branch: Branch<A>) => Tree<A>): Tree<A> =>
    isLeaf(self) ? self : f(self),
)
 
/**
 * Run a function to change the value, but not the type, of the top level
 * node of the given tree.
 * @typeParam A Underlying tree type.
 * @param self Tree on which to run the given function.
 * @param f Function to apply on the root node value.
 * @returns The given tree with its root node value set to the result of the given function.
 * @category basic
 * @function
 */
export const modValue: {
  <A>(self: Tree<A>, f: (a: A) => A): Tree<A>
  <A>(f: (a: A) => A): (self: Tree<A>) => Tree<A>
} = dual(
  2,
  <A>(self: Tree<A>, f: (a: A) => A): Tree<A> =>
    setValue(self, pipe(self, getValue, f)),
)
 
/**
 * Run a function to change the root node forest. If the tree is a {@link Leaf}
 * the given function will receive the empty array as a parameter, if it returns
 * any trees then leaves will be turned into a {@link Branch}es, and if it
 * returns the empty array branches will be turned into leaves.
 * @typeParam A Underlying tree type.
 * @param self Tree on which to run the given function.
 * @param f Function to apply on the root forest.
 * @returns The given tree with its root forest set to the result of the given function.
 * @category basic
 * @function
 */
export const modForest: {
  <A>(self: Tree<A>, f: EndoOf<readonly Tree<A>[]>): Tree<A>
  <A>(f: EndoOf<readonly Tree<A>[]>): (self: Tree<A>) => Tree<A>
} = dual(
  2,
  <A>(self: Tree<A>, f: EndoOf<readonly Tree<A>[]>): Tree<A> =>
    pipe(self, Pair.fanout(getValue, flow(getForest, f)), tree.tupled),
)
 
/**
 * Same as {@link modForest} but only accepts branches, so the given function is
 * guaranteed to get a non empty forest as its argument.
 * @typeParam A Underlying tree type.
 * @param f Function to apply on the root forest.
 * @returns The given branch with its root forest set to the result of the given function.
 * @category basic
 * @function
 */
export const modBranchForest =
  <A>(f: (a: ForestOf<A>) => ForestOf<A>): ((self: Branch<A>) => Branch<A>) =>
  /** Branch on which to run the given function. */
  self =>
    setForest(self, pipe(self, getBranchForest, f))
 
/**
 * Return the first child tree of a branch.
 * @example
 * import * as Tree from 'effect-tree'
 *
 * const branch = Tree.branch(2, [Tree.of(1), Tree.of(2)])
 *
 * expect(Tree.firstChild(branch)).toEqual(Tree.of(1))
 * @typeParam A Underlying tree type.
 * @param self tree to navigate.
 * @returns The tree that is first in the forest of the given branch.
 * @category basic
 * @function
 */
export const firstChild = <A>(self: Branch<A>): Tree<A> =>
  pipe(self, getBranchForest, Array.headNonEmpty)
 
/**
 * Return the last child tree of a branch.
 * @example
 * import * as Tree from 'effect-tree'
 *
 * const branch = Tree.branch(2, [Tree.of(1), Tree.of(2)])
 *
 * expect(Tree.lastChild(branch)).toEqual(Tree.of(2))
 * @typeParam A Underlying tree type.
 * @param self tree to navigate.
 * @returns The tree that is last in the forest of the given branch.
 * @category basic
 * @function
 */
export const lastChild = <A>(self: Branch<A>): Tree<A> =>
  pipe(self, getBranchForest, Array.lastNonEmpty)
 
const _nthChild = <A>(n: number, self: Tree<A>): Option<Tree<A>> =>
  pipe(
    self,
    match({
      onLeaf: K(none<Tree<A>>()),
      onBranch: (_, forest) =>
        Array.get(forest, n + (n < 0 ? forest.length : 0)),
    }),
  )
 
/**
 * Return the Nth child tree of a tree or `Option.none()` if index is
 * out-of-bounds or if given tree is a leaf.
 *
 * Negative indexes are handled as offsets from the end of the forest with `-1`
 * being the last child, `-2` the child before it, and so on.
 * @typeParam A Underlying tree type.
 * @param n index of requested node in parent forest. Negative indexes are
 * accepted.
 * @param self Node will be taken from this tree's forest.
 * @returns An optional tree.
 * @category basic
 * @function
 */
export const nthChild: {
  <A>(n: number, self: Tree<A>): Option<Tree<A>>
  <A>(self: Tree<A>): (n: number) => Option<Tree<A>>
  flip: (n: number) => <A>(self: Tree<A>) => Option<Tree<A>>
} = Object.assign(
  dual(2, <A>(n: number, self: Tree<A>) => _nthChild(n, self)),
  {
    flip:
      (n: number) =>
      <A>(self: Tree<A>) =>
        _nthChild(n, self),
  },
)
 
const _drill = <A>(path: number[], self: Tree<A>): Option<Tree<A>> => {
  const [head, ...tail] = path
  if (head === undefined) return none()
 
  let child = nthChild(head, self)
  if (isNone(child)) return none()
 
  for (const index of tail) {
    child = nthChild(index, child.value)
    if (isNone(child)) return none()
  }
 
  return child
}
 
/**
 * Drill down to get the child node at a given index path or none. Negative
 * indexes are handled as in {@link nthChild}: as offsets from the end
 * of the forest with `-1` being the last child, `-2` the child before it, and
 * so on.
 *
 * An empty path will return the given tree.
 * @typeParam A Underlying tree type.
 * @param path a possibly empty array of numeric indexes that form a path from
 * root node to some child node.
 * accepted.
 * @param self node will be taken from the forest of this node.
 * @returns An optional tree.
 * @category basic
 * @function
 */
export const drill: {
  <A>(path: number[], self: Tree<A>): Option<Tree<A>>
  <A>(self: Tree<A>): (path: number[]) => Option<Tree<A>>
  flip: (path: number[]) => <A>(self: Tree<A>) => Option<Tree<A>>
} = Object.assign(Function.dual(2, _drill), {
  flip:
    (path: number[]) =>
    <A>(self: Tree<A>) =>
      drill(path, self),
})
 
const _sliceForest = <A>(self: Tree<A>, low: number, high?: number) =>
  pipe(
    self,
    match({
      onLeaf: _ => [] as Tree<typeof _>[],
      onBranch: (_, forest) => forest.slice(low, high),
    }),
  )
 
/**
 * Get a slice from the forest of the given tree. An empty path will return the
 * given tree.
 * @typeParam A Underlying tree type.
 * @param self The tree to query.
 * accepted.
 * @param low Index of slice start.
 * @param high Optional length of slice. Default is a single tree node.
 * @returns Possibly empty list of trees.
 * @category basic
 * @function
 */
export const sliceForest: {
  <A>(self: Tree<A>, low: number, high?: number): Tree<A>[]
  flip: <A>(self: Tree<A>) => (low: number, high?: number) => Tree<A>[]
  curry: (low: number, high?: number) => <A>(self: Tree<A>) => Tree<A>[]
} = Object.assign(_sliceForest, {
  curry:
    (low: number, high?: number) =>
    <A>(self: Tree<A>) =>
      _sliceForest(self, low, high),
  flip:
    <A>(self: Tree<A>) =>
    (low: number, high?: number) =>
      _sliceForest(self, low, high),
})