UNPKG

1.85 kBJavaScriptView Raw
1import lodashMerge from "lodash.merge";
2
3/**
4 * @param {*=} item
5 * @returns {boolean}
6 */
7export function isNil(item) {
8 return item === null || item === undefined;
9}
10
11/**
12 * @param {*=} item
13 * @returns {boolean}
14 */
15export function isPlainObject(item) {
16 return (
17 typeof item === "object" &&
18 !isNil(item) &&
19 item.constructor === Object &&
20 Object.prototype.toString.call(item) === "[object Object]"
21 );
22}
23
24/**
25 * @param {object} object The destination object.
26 * @param {...object} [sources] The source objects.
27 * @returns {object} Returns `object`.
28 */
29export const merge = lodashMerge;
30
31/**
32 * @param {object} data The object to serialize
33 * @param [result]
34 * @param [path]
35 * @returns {object.<string, *>}
36 */
37export function flatten(data, result = {}, path = "") {
38 for (const key of Object.keys(data)) {
39 let resultPath = `${path}.${key}`;
40 if (path === "") {
41 resultPath = key;
42 }
43 const value = data[key];
44
45 if (!isPlainObject(value)) {
46 result[resultPath] = value;
47 } else {
48 flatten(value, result, resultPath);
49 }
50 }
51
52 return result;
53}
54
55/**
56 * @param {object} data
57 * @returns {object}
58 */
59export function unFlatten(data) {
60 const result = {};
61 for (const key of Object.keys(data)) {
62 const value = data[key];
63 const keyParts = key.split(".");
64
65 let tmpObject = result;
66 for (const part of keyParts.slice(0, keyParts.length - 1)) {
67 if (isNil(tmpObject[part]) || !isPlainObject(tmpObject[part])) {
68 tmpObject[part] = {};
69 }
70 tmpObject = tmpObject[part];
71 }
72 tmpObject[keyParts[keyParts.length - 1]] = value;
73 }
74
75 return result;
76}
77
78/**
79 * @param input
80 */
81export function camelToSnakeCase(input) {
82 return input
83 .replace(/(.)([A-Z][a-z]+)/g, "$1_$2")
84 .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
85 .toLowerCase()
86 .trim();
87}