Skip to content

Instantly share code, notes, and snippets.

@SparK-Cruz
Created August 12, 2024 14:46
Show Gist options
  • Save SparK-Cruz/fd269739c81124f2a2ad1c5edbb3eea0 to your computer and use it in GitHub Desktop.
Save SparK-Cruz/fd269739c81124f2a2ad1c5edbb3eea0 to your computer and use it in GitHub Desktop.
Functions to read and write on graphs with dotted string keys
const obj = {
a: {
a: 5
},
b: {
a: 8
}
};
console.log(readGraph(obj, 'a.a')); // 5
console.log(readGraph(obj, 'b.a')); // 8
console.log(writeGraph(obj, 'a.a', 10));
console.log(readGraph(obj, 'a.a')); // 10
console.log(writeGraph(obj, 'a.b', 7));
console.log(readGraph(obj, 'a.b')); // 7
console.log(writeGraph(obj, 'c.a.a', 3));
console.log(readGraph(obj, 'c.a.a')); // 3
console.log(readGraph(obj, 'a')); // { a: 10, b: 7 }
function readGraph(obj, path) {
const names = path.split('.');
return names.reduce((prev, name) => {
if (null === prev
|| typeof prev === 'undefined'
) {
return undefined;
}
return prev[name];
}, obj);
}
function writeGraph(obj, path, value) {
const names = path.split('.');
const tip = names.pop();
obj = names.reduce((prev, name) => {
if (null === prev[name]
|| typeof prev[name] === 'undefined'
) {
prev[name] = {};
}
return prev[name];
}, obj);
obj[tip] = value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment