All files / src/search treeFind.ts

92.31% Statements 24/26
83.33% Branches 20/24
100% Functions 7/7
92% Lines 23/25

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