All files / src/bundle/strategies per-route.ts

97.5% Statements 39/40
93.33% Branches 14/15
100% Functions 15/15
97.29% Lines 36/37

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    1x             1x 215x   1x 81x 60x 60x 43x 43x     81x     1x 81x 81x 378x     1x 79x 79x 61x     18x 42x 39x   3x         1x 60x         60x 60x 76x     76x         60x 60x     1x 1x 14x 14x   21x       21x    
import { ModelItem, Container, RootContainer } from '../model/types';
import { BundleConfig, Strategy } from '../types';
import { extractDuplicates } from '../utils/array';
 
interface RouteGroup {
  children: RouteGroup[];
  classIds: string[];
}
 
const isContainer = (item: ModelItem | RootContainer): item is Container =>
  Object.prototype.hasOwnProperty.call(item, 'children');
 
const moveFirstChildren = (routeGroup: RouteGroup, depth: number): RouteGroup => {
  routeGroup.children.forEach((child, index) => {
    moveFirstChildren(child, depth - 1);
    if (index === 0 || depth < 0) {
      routeGroup.classIds.push(...child.classIds);
      child.classIds = [];
    }
  });
  return routeGroup;
};
 
const extractClassIds = (routeGroup: RouteGroup, bundles: BundleConfig[] = []): BundleConfig[] => {
  bundles.push(routeGroup.classIds);
  routeGroup.children.forEach((child) => extractClassIds(child, bundles));
  return bundles.filter((bundle) => bundle.length > 0).map((classIds) => [...new Set(classIds)]);
};
 
const getChildrenWithoutRoute = (routeGroup: RouteGroup, modelItem: ModelItem) => {
  routeGroup.classIds.push(modelItem.classId);
  if (!isContainer(modelItem)) {
    return;
  }
 
  modelItem.children.forEach((child) => {
    if ((<Container>child).route) {
      routeGroup.children.push(createRouteTree(child));
    } else {
      getChildrenWithoutRoute(routeGroup, child);
    }
  });
};
 
const createRouteTree = (node: ModelItem | RootContainer) => {
  const routeGroup: RouteGroup = {
    classIds: 'classId' in node ? [node.classId] : [],
    children: [],
  };
 
  if (isContainer(node)) {
    node.children.forEach((child) => {
      Iif (isContainer(child) && child.route) {
        routeGroup.children.push(createRouteTree(child));
      } else {
        getChildrenWithoutRoute(routeGroup, child);
      }
    });
  }
 
  routeGroup.classIds = [...new Set(routeGroup.classIds)];
  return routeGroup;
};
 
export const perRouteStrategy =
  (depth = Number.MAX_VALUE): Strategy =>
  (model: RootContainer[]): BundleConfig[] =>
    extractDuplicates(
      model
        .map((page) => ({
          classIds: [],
          children: [createRouteTree(page)],
        }))
        .reduce((bundles, group) => [...bundles, ...extractClassIds(moveFirstChildren(group, Math.max(0, depth)))], []),
    );