Skip to content

Commit

Permalink
feat(utils): add flatObject and normalizeFlattedObject functions
Browse files Browse the repository at this point in the history
  • Loading branch information
wewoor authored and mumiao committed Apr 28, 2021
1 parent 48c8984 commit cb93d7c
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions src/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,73 @@ export function mergeFunctions(...funcs) {
export function randomId() {
return Date.now() + Math.round(Math.random() * 1000);
}

export function mergeObjects(source: object, target: object) {
for (const prop in target) {
if (typeof source[prop] === 'object' && target[prop]) {
source[prop] = mergeObjects(source[prop], target[prop]);
} else {
source[prop] = target[prop];
}
}
return source;
}

/**
* It's used convert an object to a flatted object,
* eg: { a: { b: 'test' }}, result is : { 'a.b': 'test' }
* @param target flat target
*/
export function flatObject(target: object): object {
const flatted = {};
const recurse = (parent: string, target: object) => {
for (const prop in target) {
if (prop) {
const value = target[prop];
const path = parent ? `${parent}.${prop}` : prop;
if (typeof value === 'object') {
recurse(path, value);
} else {
flatted[path] = value;
}
}
}
};
recurse('', target);
return flatted;
}

/**
* It's used convert a flatted object to a normal object,
* eg: { 'a.b': 'test' }, result is : { a: { b: 'test' }}
* @param target flat target
*/
export function normalizeFlattedObject(target: object): object {
let normalized = {};

for (const prop in target) {
if (prop) {
const flattedProps = prop.split('.');
let prevProp = '';
let root = {};
let prevObj = root;
for (let i = 0; i < flattedProps.length; ++i) {
if (i === flattedProps.length) break;
const key = flattedProps[i];
const current = { [key]: '' };

if (prevProp) {
prevObj[prevProp] = current;
}
prevObj = current;
prevProp = key;
if (i === 0) {
root = current;
}
}
prevObj[prevProp] = target[prop];
normalized = mergeObjects(normalized, root);
}
}
return normalized;
}

0 comments on commit cb93d7c

Please sign in to comment.