All files pickAll.ts

88.46% Statements 23/26
70.59% Branches 12/17
100% Functions 7/7
88% Lines 22/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 611x         1x         1x 6x   1x   6x 6x 5x   1x     2x             1x 4x 4x           1x 2x 2x 2x 4x   2x       1x 1x   1x                    
import * as R from 'ramda';
 
 
type BaseT = Record<string, any>;
 
export const pickAll = <T extends BaseT>(
  key: string,
  childKey: string,
  data: T[] | 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)) {
        return acc;
      }
      return childKey && node[childKey] && !R.isEmpty(node[childKey]) ? Tree.reduce(findFn, acc)(node[childKey]) : acc;
    }),
    find: R.curry((fn: any, init: any[], node: T[]) => {
      return R.pipe(
        R.map(Tree.reduce(fn, init)),
        R.flatten,
        R.union(init)
      )(node as T[]);
    })
  };
  const reducerFn = (arr: any[], data: T) => {
    Eif (data[key]) {
      return childKey ? arr.concat([R.pick([key], 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 [];
    }
  }
};