All files / search treePaths.ts

89.29% Statements 25/28
83.33% Branches 20/24
100% Functions 7/7
88.89% Lines 24/27

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 741x                 1x         1x 8x   1x   8x 8x 1x   7x     2x           1x 6x       1x   5x         1x 2x       2x 2x 2x 6x   2x       1x 1x     1x                      
import * as R from 'ramda';
 
interface Target {
  key: string;
  value?: any;
}
 
type BaseT = Record<string, any>;
 
export const treePaths = <T extends BaseT>(
  target: Target,
  childKey: string,
  data: Record<string, T>,
): string[] => {
  const hasChildren = (node: T) => {
    return R.hasPath([childKey], node) && !R.isEmpty(node[childKey]);
  };
  const Tree: any = {
    reduce: R.curry((reducerFn: any, init: any[], preNode: T, node: T) => {
      const acc = reducerFn(init, preNode, node);
      if (!hasChildren(node) && node[target.key] === target.value) {
        return acc.concat([preNode.path]);
      }
      return node[childKey] && !R.isEmpty(node[childKey]) ? Tree.reduce(findFn, [], node)(node[childKey]) : acc;
    }),
    find: R.curry((findFn: any, init: any[], preNode: T, node: T[]) => {
      return R.pipe(
        R.map(Tree.reduce(findFn, init, preNode)),
        R.flatten
      )(node as T[]);
    })
  };
  const reducerFn = (arr: any[], _preNode: T, data: T) => {
    if (
      (target.value && data[target.key] && data[target.key] === target.value) ||
      (!target.value && data[target.key])
    ) {
      return arr.concat([data.path]);
    } else {
      return arr;
    }
 
  };
 
  const findFn = (arr: any[], preNode: Record<string, T>, data: Record<string, T>) => {
    Iif(!data || R.isEmpty(data)){
      return arr;
    }
 
    const keys = Object.keys(data);
    const result: any = [];
    keys.map((key: string) => {
      result.push(data[key]);
    });
    return Tree.find(reducerFn, arr, preNode)(result);
  }
 
 
  const type = R.type(data);
  switch (type) {
    case 'Object': {
 
      return Tree.reduce(findFn, [], {})(data);
    }
    case 'Array': {
      return Tree.find(reducerFn, [], {})(data);
    }
    default: {
      return [];
    }
  }
};