@nka212bg/backend-utils 0.1.13 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/misc.js +72 -0
- package/package.json +1 -1
package/misc.js
CHANGED
|
@@ -512,3 +512,75 @@ exports.iterateObject = (obj, callback) => {
|
|
|
512
512
|
}
|
|
513
513
|
}
|
|
514
514
|
};
|
|
515
|
+
|
|
516
|
+
exports.flattenObject = (obj, parentKey = "", result = {}) => {
|
|
517
|
+
for (let key in obj) {
|
|
518
|
+
const newKey = parentKey ? `${parentKey}.${key}` : key;
|
|
519
|
+
if (typeof obj[key] === "object" && obj[key] !== null) {
|
|
520
|
+
this.flattenObject(obj[key], newKey, result);
|
|
521
|
+
} else {
|
|
522
|
+
result[newKey] = obj[key];
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return result;
|
|
526
|
+
};
|
|
527
|
+
|
|
528
|
+
exports.unflattenObject = (obj) => {
|
|
529
|
+
let result = {};
|
|
530
|
+
|
|
531
|
+
for (const key in obj) {
|
|
532
|
+
if (obj.hasOwnProperty(key)) {
|
|
533
|
+
const keys = key.split(".");
|
|
534
|
+
keys.reduce((acc, part, index) => {
|
|
535
|
+
if (index === keys.length - 1) {
|
|
536
|
+
acc[part] = obj[key];
|
|
537
|
+
} else {
|
|
538
|
+
acc[part] = acc[part] || {};
|
|
539
|
+
}
|
|
540
|
+
return acc[part];
|
|
541
|
+
}, result);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
return result;
|
|
546
|
+
};
|
|
547
|
+
|
|
548
|
+
exports.mergeObjects = (oldObj, newObj) => {
|
|
549
|
+
const tempOldObj = this.flattenObject(oldObj);
|
|
550
|
+
const tempNewObj = this.flattenObject(newObj);
|
|
551
|
+
|
|
552
|
+
for (const key in tempNewObj) {
|
|
553
|
+
if (isNaN(tempNewObj[key])) {
|
|
554
|
+
tempOldObj[key] = tempNewObj[key];
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
tempOldObj[key] = (Number(tempOldObj[key]) || 0) + (Number(tempNewObj[key]) || 1);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
return this.unflattenObject(tempOldObj);
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
exports.deepJsonParse = (obj) => {
|
|
564
|
+
try {
|
|
565
|
+
obj = JSON.parse(obj);
|
|
566
|
+
} catch {}
|
|
567
|
+
if (!obj || typeof obj != "object") return obj;
|
|
568
|
+
|
|
569
|
+
for (const key in obj) {
|
|
570
|
+
try {
|
|
571
|
+
obj[key] = JSON.parse(obj[key]);
|
|
572
|
+
} catch {}
|
|
573
|
+
if (!obj[key] || typeof obj[key] != "object") continue;
|
|
574
|
+
obj[key] = this.deepJsonParse(obj[key]);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
return obj;
|
|
578
|
+
};
|
|
579
|
+
|
|
580
|
+
exports.shortenText = (text, { maxLength = 100, filler = "[-]" } = {}) => {
|
|
581
|
+
if (text.length <= maxLength) {
|
|
582
|
+
return text;
|
|
583
|
+
}
|
|
584
|
+
const halfLength = Math.floor((maxLength - 3) / 2);
|
|
585
|
+
return text.slice(0, halfLength) + filler + text.slice(-halfLength);
|
|
586
|
+
};
|