Created
August 12, 2024 14:46
-
-
Save SparK-Cruz/fd269739c81124f2a2ad1c5edbb3eea0 to your computer and use it in GitHub Desktop.
Functions to read and write on graphs with dotted string keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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