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 | 1x 1x 2x 30x 2x 30x 30x 1x 29x 4x 2x 26x 2x 24x 2x 4x 4x 4x 26x 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, 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) => {
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 [];
}
}
};
|