generator-begcode
Version:
Spring Boot + Angular/React/Vue in one handy generator
28 lines (27 loc) • 1.3 kB
JavaScript
import { camelCase, upperFirst } from 'lodash-es';
import { upperFirstCamelCase } from './string.js';
const flatChoices = (choices) => choices.map(choice => (typeof choice === 'string' ? choice : choice.value)).filter(Boolean);
export const applyDerivedProperty = (data, property, possibleValues, { addAny, addNo, defaultValue = 'no' } = {}) => {
const camelCaseProp = camelCase(property);
let actualValue = data[camelCaseProp] ?? defaultValue;
actualValue = actualValue === false && possibleValues.includes('no') ? 'no' : actualValue;
const flattenedChoices = flatChoices(possibleValues);
let isAny = false;
for (const value of flattenedChoices) {
const valueProterty = value.includes('-') ? upperFirstCamelCase(value) : upperFirst(value);
const isProperty = Array.isArray(actualValue) ? actualValue.includes(value) : actualValue === value;
data[`${camelCaseProp}${valueProterty}`] ??= isProperty;
if (isProperty && value !== 'no') {
isAny = true;
}
}
if (addAny) {
data[`${camelCaseProp}Any`] ??= isAny;
}
if (addNo) {
if (flattenedChoices.includes('no')) {
throw new Error('Possible values already include "no"');
}
data[`${camelCaseProp}No`] ??= !isAny;
}
};