svelte-settings
Version:
> [!WARNING] > This project is a work in progress. Do not use it in any of your projects yet.
51 lines (50 loc) • 1.46 kB
JavaScript
export function getDeep(obj, path) {
return path.reduce((o, k) => (o && typeof o === 'object' ? o[k] : undefined), obj);
}
export function setDeep(obj, path, value) {
let part = obj;
// select the part containing the key
for (let i = 0; i < path.length - 1; i++) {
const key = path[i];
part = part[key] ??= {};
}
part[path.at(-1)] = value;
}
export function deleteDeep(obj, path) {
let part = obj;
for (let i = 0; i < path.length - 1; i++) {
const key = path[i];
part = part[key] ??= {};
}
delete part[path.at(-1)];
}
function isObject(item) {
return item && typeof item === 'object' && !Array.isArray(item);
}
/**
* Deep merge two objects.
* https://stackoverflow.com/a/34749873
* @param target
* @param ...sources
*/
export function mergeDeep(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key])
Object.assign(target, { [key]: {} });
mergeDeep(target[key], source[key]);
}
else {
Object.assign(target, { [key]: source[key] });
}
}
}
return mergeDeep(target, ...sources);
}
export function deepEqual(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}