@nerdware/ddb-single-table
Version:
A schema-based DynamoDB modeling tool, high-level API, and type-generator built to supercharge single-table designs!⚡
35 lines (34 loc) • 1.53 kB
JavaScript
import { isArray, isPlainObject, isUndefined } from "@nerdware/ts-type-safety-utils";
/**
* This function creates a recursive value converter that applies the provided `valueConverter`
* to all non-falsy values in the input object or array.
*
* @template AllowedReturnTypes - Union of allowed return types for the `valueConverter` function.
* @param valueConverter - A fn that returns a converted-value OR `undefined` if no conversion was applied.
* @returns A function that recursively applies value-conversion to its `value` parameter.
*/
export const getRecursiveValueConverter = (valueConverter) => {
// This function will be called recursively to convert nested values
const recursiveConversionFn = (value) => {
// First, return falsey values as-is
if (!value)
return value;
// Run the value through the provided valueConverter
const convertedValue = valueConverter(value);
if (!isUndefined(convertedValue))
return convertedValue;
// Check for types that necessitate recursive calls
if (isArray(value))
return value.map(recursiveConversionFn);
if (isPlainObject(value)) {
const result = {};
for (const itemKey of Object.keys(value)) {
result[itemKey] = recursiveConversionFn(value[itemKey]);
}
return result;
}
// If none of the above apply, return the value as-is
return value;
};
return recursiveConversionFn;
};