Skip to content

Instantly share code, notes, and snippets.

@witt3rd
Created May 31, 2019 12:33
Show Gist options
  • Save witt3rd/34adb184956daa1cee3d20c49cb2440c to your computer and use it in GitHub Desktop.
Save witt3rd/34adb184956daa1cee3d20c49cb2440c to your computer and use it in GitHub Desktop.
// --- Object path operations
export const objGetPathList = ({ path }) => {
let pathList;
if (Array.isArray(path)) {
pathList = path;
} else if (typeof path === "string") {
pathList = path.split("/");
}
return pathList;
};
export const objTraverseTo = ({ root, pathList, create = false }) => {
let obj = root;
for (let i = 0; i < pathList.length - 1; i++) {
const key = pathList[i];
let nextObj = obj[key];
if (!nextObj) {
if (!create) return;
obj[key] = nextObj = {};
}
obj = nextObj;
}
return obj;
};
export const objGetAtPath = ({ root, path }) => {
const pathList = objGetPathList({ path });
if (!pathList || !pathList.length) return;
const obj = objTraverseTo({ root, pathList });
if (!obj) return;
return obj[pathList[pathList.length - 1]];
};
export const objSetAtPath = ({ root, path, value }) => {
const pathList = objGetPathList({ path });
if (!pathList || !pathList.length) return;
const obj = objTraverseTo({ root, pathList, create: true });
if (!obj) return;
obj[pathList[pathList.length - 1]] = value;
return root;
};
export const objAddAtPath = ({ root, path, value }) => {
const pathList = objGetPathList({ path });
if (!pathList || !pathList.length) return;
const obj = objTraverseTo({
root,
pathList,
create: true
});
const key = pathList[pathList.length - 1];
const list = obj[key] || [];
const len = list.push(value);
obj[key] = list;
return len - 1;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment