2023-07-12 17:40:41 +00:00
|
|
|
import * as plugins from '../smartobject.plugins.js';
|
2022-03-07 14:28:32 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* adds an object to the parent object if it doesn't exists
|
|
|
|
* @param parentObject
|
|
|
|
* @param childParam
|
|
|
|
* @param logBool
|
|
|
|
* @returns {boolean}
|
|
|
|
*/
|
2023-07-12 17:40:41 +00:00
|
|
|
export const smartAdd = (
|
2022-03-07 14:28:32 +00:00
|
|
|
parentObject: object,
|
|
|
|
childParam: string,
|
|
|
|
valueArg: any = {},
|
|
|
|
optionsArg?: {
|
|
|
|
interpretDotsAsLevel: boolean;
|
|
|
|
}
|
|
|
|
): typeof parentObject & any => {
|
|
|
|
optionsArg = {
|
|
|
|
interpretDotsAsLevel: true,
|
2023-07-12 17:40:41 +00:00
|
|
|
...optionsArg,
|
2022-03-07 14:28:32 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
let paramLevels: string[];
|
|
|
|
let referencePointer: any = parentObject;
|
|
|
|
if (optionsArg.interpretDotsAsLevel) {
|
|
|
|
paramLevels = childParam.split('.');
|
|
|
|
} else {
|
|
|
|
paramLevels = [childParam];
|
|
|
|
}
|
|
|
|
|
|
|
|
for (let i = 0; i !== paramLevels.length; i++) {
|
|
|
|
const varName: string = paramLevels[i];
|
|
|
|
|
|
|
|
// is there a next variable ?
|
|
|
|
const varNameNext: string = (() => {
|
|
|
|
if (paramLevels[i + 1]) {
|
|
|
|
return paramLevels[i + 1];
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
})();
|
|
|
|
|
|
|
|
// build the tree in parentObject
|
|
|
|
if (!referencePointer[varName] && !varNameNext) {
|
|
|
|
referencePointer[varName] = valueArg;
|
|
|
|
referencePointer = null;
|
|
|
|
} else if (!referencePointer[varName] && varNameNext) {
|
|
|
|
referencePointer[varName] = {};
|
|
|
|
referencePointer = referencePointer[varName];
|
|
|
|
} else if (referencePointer[varName] && varNameNext) {
|
|
|
|
referencePointer = referencePointer[varName];
|
|
|
|
} else {
|
|
|
|
throw new Error('Something is strange!');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return parentObject;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* gets an object from the parent object using dots as levels by default
|
|
|
|
* @param parentObject
|
|
|
|
* @param childParam
|
|
|
|
* @param optionsArg
|
|
|
|
*/
|
|
|
|
export const smartGet = <T>(
|
|
|
|
parentObject: object,
|
|
|
|
childParam: string,
|
|
|
|
optionsArg?: {
|
|
|
|
interpretDotsAsLevel: boolean;
|
|
|
|
}
|
|
|
|
): T => {
|
|
|
|
optionsArg = {
|
|
|
|
interpretDotsAsLevel: true,
|
2023-07-12 17:40:41 +00:00
|
|
|
...optionsArg,
|
2022-03-07 14:28:32 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
let paramLevels: string[];
|
|
|
|
if (optionsArg.interpretDotsAsLevel) {
|
|
|
|
paramLevels = childParam.split('.');
|
|
|
|
} else {
|
|
|
|
paramLevels = [childParam];
|
|
|
|
}
|
|
|
|
|
|
|
|
let referencePointer: any = parentObject;
|
|
|
|
for (const level of paramLevels) {
|
|
|
|
if (referencePointer[level as any]) {
|
|
|
|
referencePointer = referencePointer[level as any];
|
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return referencePointer as T;
|
2023-07-12 17:40:41 +00:00
|
|
|
};
|