smartobject/ts/tools/smart_add_get.ts

92 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-03-07 14:28:32 +00:00
import * as plugins from '../smartobject.plugins';
/**
* adds an object to the parent object if it doesn't exists
* @param parentObject
* @param childParam
* @param logBool
* @returns {boolean}
*/
export const smartAdd = (
parentObject: object,
childParam: string,
valueArg: any = {},
optionsArg?: {
interpretDotsAsLevel: boolean;
}
): typeof parentObject & any => {
optionsArg = {
interpretDotsAsLevel: true,
...optionsArg
};
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,
...optionsArg
};
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;
};