All files / src/app/core/models/category-view category-view.model.ts

100% Statements 12/12
94.11% Branches 16/17
100% Functions 4/4
100% Lines 12/12

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                        179x 452x 265x   187x 35x     152x         311x 311x                     179x 1030x 3x   1027x    
import { CategoryTree } from 'ish-core/models/category-tree/category-tree.model';
import { Category } from 'ish-core/models/category/category.model';
 
/**
 * View on a {@link Category} with additional methods for navigating to sub categories or category path
 */
export interface CategoryView extends Category {
  children: string[];
  hasChildren: boolean;
  pathElements: Category[];
}
 
export function createCategoryView(tree: CategoryTree, uniqueId: string): CategoryView {
  if (!tree || !uniqueId) {
    return;
  }
  if (!tree.nodes[uniqueId] && !tree.nodes[translateRef(tree, uniqueId)]) {
    return;
  }
 
  return {
    ...tree.nodes[translateRef(tree, uniqueId)],
    children: tree.edges[translateRef(tree, uniqueId)] || [],
    hasChildren: !!tree.edges[translateRef(tree, uniqueId)] && !!tree.edges[translateRef(tree, uniqueId)].length,
    pathElements: (tree.nodes[translateRef(tree, uniqueId)]?.categoryPath || [])
      .map(path => tree.nodes[translateRef(tree, path)])
      .filter(x => !!x),
  };
}
 
/**
 * Translates a given uniqueId into a key value that can be used to retrieve category data from store.
 *
 * @param tree the category tree structure to lookup `categoryRef` translation value
 * @param uniqueId the key value, either in category-path or category-ref notation
 * @returns the key value that can be used to resolve category data
 */
export function translateRef(tree: CategoryTree, uniqueId: string): string {
  if (!tree || !uniqueId) {
    return;
  }
  return tree.categoryRefs[uniqueId] ?? uniqueId;
}