@augment-vir/common
Version:
A collection of augments, helpers types, functions, and classes for any JavaScript environment.
73 lines (72 loc) • 2.08 kB
JavaScript
import { check } from '@augment-vir/assert';
import { mapObjectValues } from '../object/map-values.js';
import { omitObjectKeys } from '../object/object-keys.js';
/**
* Determine if the given input should be preserved in the selection output, meaning it won't be
* recursed into.
*
* @ignore
*/
export function shouldPreserveInSelectionSet(input) {
return check.isPrimitive(input) || input instanceof RegExp || input instanceof Promise;
}
/**
* Performs a SQL-like nested selection on an object, extracting the selected values.
*
* @category Selection
* @category Package : @augment-vir/common
* @example
*
* ```ts
* import {selectFrom} from '@augment-vir/common';
*
* selectFrom(
* [
* {
* child: {
* grandChild: 'hi',
* grandChild2: 3,
* grandChild3: /something/,
* },
* },
* {
* child: {
* grandChild: 'hi',
* grandChild2: 4,
* grandChild3: /something/,
* },
* },
* ],
* {
* child: {
* grandChild2: true,
* },
* },
* );
* // output is `[{child: {grandChild2: 3}}, {child: {grandChild2: 4}}]`
* ```
*
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function selectFrom(originalObject, selectionSet) {
if (Array.isArray(originalObject)) {
return originalObject.map((originalEntry) => selectFrom(originalEntry, selectionSet));
}
const keysToRemove = [];
return omitObjectKeys(mapObjectValues(originalObject, (key, value) => {
const selection = selectionSet[key];
if (selection === true) {
return value;
}
else if (!selection) {
keysToRemove.push(key);
return undefined;
}
else if (shouldPreserveInSelectionSet(value)) {
return value;
}
else {
return selectFrom(value, selection);
}
}), keysToRemove);
}