Files
watchstate/frontend/utils/index.js
Abdulmhsen B. A. A 488596dede More WebUI updates.
2024-05-03 11:55:50 +03:00

45 lines
1.2 KiB
JavaScript

const ag = (obj, path, defaultValue = null, separator = '.') => {
const keys = path.split(separator);
let at = obj;
for (let key of keys) {
if (typeof at === 'object' && at !== null && key in at) {
at = at[key];
} else {
return defaultValue;
}
}
return at;
}
const ag_set = (obj, path, value, separator = '.') => {
const keys = path.split(separator);
let at = obj;
while (keys.length > 0) {
if (keys.length === 1) {
if (typeof at === 'object' && at !== null) {
at[keys.shift()] = value;
} else {
throw new Error(`Cannot set value at this path (${path}) because it's not an object.`);
}
} else {
const key = keys.shift();
if (!at[key]) {
at[key] = {};
}
at = at[key];
}
}
return obj;
}
const humanFileSize = (bytes = 0, showUnit = true, decimals = 2, mod = 1000) => {
const sz = 'BKMGTP';
const factor = Math.floor((bytes.toString().length - 1) / 3);
return `${(bytes / (mod ** factor)).toFixed(decimals)}${showUnit ? sz[factor] : ''}`;
}
export {ag_set, ag, humanFileSize}