@yellow-ticket/seed-json-schema
Version:
Seed a JSON Schema with random values.
39 lines (38 loc) • 1.14 kB
JavaScript
import { isObject } from './is-object.js';
function mergeObjects(target, source) {
if (!isObject(target) || !isObject(source)) {
return source;
}
const result = { ...target };
for (const _key of Object.keys(source)) {
const key = _key;
const targetVal = result[key];
const sourceVal = source[key];
if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {
result[key] = [...new Set([...targetVal, ...sourceVal])];
}
else if (isObject(targetVal) && isObject(sourceVal)) {
result[key] = mergeObjects(targetVal, sourceVal);
}
else {
result[key] = sourceVal;
}
}
return result;
}
function flatten(objects) {
return objects.flatMap((obj) => {
if (typeof obj === 'boolean') {
return [obj];
}
if (obj.allOf) {
return flatten(obj.allOf);
}
return [obj];
});
}
export function merge(objects) {
return flatten(objects).reduce((acc, value) => {
return typeof value === 'boolean' ? acc : mergeObjects(acc, value);
}, {});
}