deep-state-observer
Version:
Deep state observer is an state management library that will fire listeners only when specified object node (which also can be a wildcard) was changed.
40 lines (38 loc) • 932 B
text/typescript
export default class ObjectPath {
static get(path: string[], obj, create = false) {
if (!obj) return;
let currObj = obj;
for (const currentPath of path) {
if (currentPath in currObj) {
currObj = currObj[currentPath];
} else if (create) {
currObj[currentPath] = Object.create({});
currObj = currObj[currentPath];
} else {
return;
}
}
return currObj;
}
static set(path: string[], value, obj) {
if (!obj) return;
if (path.length === 0) {
for (const key in obj) {
delete obj[key];
}
for (const key in value) {
obj[key] = value[key];
}
return;
}
const prePath = path.slice();
const lastPath = prePath.pop();
if (lastPath) {
const get = ObjectPath.get(prePath, obj, true);
if (typeof get === "object") {
get[lastPath] = value;
}
}
return value;
}
}