UNPKG

@augment-vir/common

Version:

A collection of augments, helpers types, functions, and classes for any JavaScript environment.

64 lines (63 loc) 1.81 kB
import { check } from '@augment-vir/assert'; import { selectFrom, shouldPreserveInSelectionSet } from './select-from.js'; /** * The same as {@link selectFrom} except that the final output is collapsed until the first nested * value that has more than 1 key or that is not an object. * * @category Selection * @category Package : @augment-vir/common * @example * * ```ts * import {selectCollapsedFrom} from '@augment-vir/common'; * * selectCollapsedFrom( * [ * { * child: { * grandChild: 'hi', * grandChild2: 3, * grandChild3: /something/, * }, * }, * { * child: { * grandChild: 'hi', * grandChild2: 4, * grandChild3: /something/, * }, * }, * ], * { * child: { * grandChild2: true, * }, * }, * ); * // output is `[3, 4]` * ``` * * @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) */ export function selectCollapsedFrom(originalObject, selectionSet) { const selected = selectFrom(originalObject, selectionSet); return collapseObject(selected, selectionSet); } function collapseObject(input, selectionSet) { if (shouldPreserveInSelectionSet(input)) { return input; } const keys = Object.keys(input); if (Array.isArray(input)) { return input.map((innerInput) => collapseObject(innerInput, selectionSet)); } else if (check.isLengthAtLeast(keys, 2)) { return input; } else if (check.isLengthAtLeast(keys, 1) && check.isObject(selectionSet)) { return collapseObject(input[keys[0]], selectionSet[keys[0]]); } else { return input; } }