Skip to content

Instantly share code, notes, and snippets.

@RAM92
Created September 27, 2018 00:45
Show Gist options
  • Save RAM92/11d69c0c3c78064b0b6f4c6ce6b5e013 to your computer and use it in GitHub Desktop.
Save RAM92/11d69c0c3c78064b0b6f4c6ce6b5e013 to your computer and use it in GitHub Desktop.
Create javascript API object by giving the paths to the value without creating object
/**
*
* @param obj Target object
* @param pathToFunc path string e.g. "foo.bar.baz"
* @param value value to place at this path
*/
function addFunction(obj, pathToFunc, value) {
const properties = pathToFunc.split('.');
function addProperty(obj, i=0) {
const isLastProperty = i+1 === properties.length;
const currentProperty = properties[i];
if(!isLastProperty) {
let nextObj = obj[currentProperty];
if(!nextObj) {
nextObj = {}
obj[currentProperty] = nextObj;
}
addProperty(nextObj, i+1);
}
else {
obj[currentProperty] = value;
}
}
addProperty(obj);
}
const api = {};
addFunction(api, 'my.nice.api.doStuff', () => console.log('woohoo!'));
addFunction(api, 'my.nice.api.doMoreStuff', () => console.log('woohoo! ...again!'));
addFunction(api, 'my.nice.api.doEvenMoreStuff', () => console.log('even more woohoo!'));
api.my.nice.api.doStuff();
api.my.nice.api.doMoreStuff();
api.my.nice.api.doEvenMoreStuff();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment