@o3r/core
Version:
Core of the Otter Framework
71 lines • 2.54 kB
JavaScript
const defaultConstruct = (data) => data;
const isDate = (data) => data instanceof Date && !Number.isNaN(data);
/**
* Check if an object is not an array or a date
* @param obj
* @param additionalMappers
*/
export function isObject(obj, additionalMappers) {
return obj instanceof Object && !Array.isArray(obj) && !additionalMappers?.some((mapper) => mapper.condition(obj)) && !isDate(obj);
}
/**
* Return a new reference of the given object
* @param obj
* @param additionalMappers
*/
export function immutablePrimitive(obj, additionalMappers) {
if (Array.isArray(obj)) {
return obj.slice();
}
const matchingPrimitive = additionalMappers?.find((mapper) => mapper.condition(obj));
const resolvedType = matchingPrimitive && ((matchingPrimitive.construct || defaultConstruct)(obj));
if (resolvedType !== undefined) {
return resolvedType;
}
if (isDate(obj)) {
return new Date(obj);
}
else if (obj instanceof Object) {
return deepFill(obj, obj, additionalMappers);
}
else {
return obj;
}
}
/**
* Deep fill of base object using source
* It will do a deep merge of the objects, overriding arrays
* All properties not present in source, but present in base, will remain
* @param base
* @param source
* @param additionalMappers Map of conditions of type mapper
*/
export function deepFill(base, source, additionalMappers) {
if (typeof source === 'undefined') {
return deepFill(base, base, additionalMappers);
}
if (!isObject(base, additionalMappers)) {
return immutablePrimitive(typeof source === 'undefined' ? base : source, additionalMappers);
}
const newObj = { ...base };
for (const key in base) {
if (source[key] === null) {
newObj[key] = immutablePrimitive(null, additionalMappers);
}
else if (key in source && typeof base[key] === typeof source[key]) {
const keyOfSource = source[key];
newObj[key] = typeof keyOfSource === 'undefined' ? immutablePrimitive(base[key], additionalMappers) : deepFill(base[key], keyOfSource, additionalMappers);
}
else {
newObj[key] = immutablePrimitive(base[key], additionalMappers);
}
}
// getting keys present in source and not present in base
for (const key in source) {
if (!(key in newObj)) {
newObj[key] = immutablePrimitive(source[key], additionalMappers);
}
}
return newObj;
}
//# sourceMappingURL=deep-fill.js.map