All files treeReduce.ts

95% Statements 19/20
85.71% Branches 12/14
100% Functions 5/5
94.74% Lines 18/19

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 571x                 1x         3x 34x   3x   34x 34x 3x   31x         2x     3x 34x       3x   31x         3x 3x   1x     2x              
import * as R from 'ramda';
 
interface Target {
  key: string;
  value?: any;
}
 
type BaseT = Record<string, any>;
 
export const treeReduce = <T extends BaseT>(
  target: Target,
  childKey: string,
  data: T[] | T,
): any[] => {
  const hasChildren = (node: T) => {
    return R.hasPath([childKey], node);
  };
  const Tree: any = {
    reduce: R.curry((reducerFn: any, init: any[], node: T) => {
      const acc = reducerFn(init, node);
      if (!hasChildren(node)) {
        return acc;
      }
      return node[childKey]
        ? node[childKey].reduce(Tree.reduce(reducerFn), acc)
        : acc;
    }),
    find: R.curry((findFn: any, init: any[], node: T[]) => {
      return R.pipe(R.map(Tree.reduce(findFn, init)), R.flatten)(node as T[]);
    })
  };
  const fn = (arr: any[], data: T) => {
    if (
      (target.value && data[target.key] && data[target.key] === target.value) ||
      (!target.value && data[target.key])
    ) {
      return arr.concat([R.omit([childKey], data)]);
    } else {
      return arr;
    }
  };
 
 
  const type = R.type(data);
  switch (type) {
    case 'Object': {
      return Tree.reduce(fn, [])(data);
    }
    case 'Array': {
      return Tree.find(fn, [])(data);
    }
    default: {
      return data as T[];
    }
  }
};