Last active
August 9, 2017 19:09
-
-
Save tomnagengast/2d12f1c02a893c744d03e2996f004416 to your computer and use it in GitHub Desktop.
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
/** | |
* Use a simple immediately-executing function to wrap the underlying "worker" function | |
* and return an object with properties for getting, setting, and checking existence | |
*/ | |
const Objectifier = (function() { | |
// Utility method to get and set objects that may or may not exist | |
const objectifier = function(splits, create, context) { | |
let result = context || window; | |
for(let i = 0, s; result && (s = splits[i]); i++) { | |
result = (s in result ? result[s] : (create ? result[s] = {} : undefined)); | |
} | |
return result; | |
}; | |
return { | |
// Creates an object if it doesn't already exist | |
set: function(name, value, context) { | |
let splits = name.split('.'), s = splits.pop(), result = objectifier(splits, true, context); | |
return result && s ? (result[s] = value) : undefined; | |
}, | |
get: function(name, create, context) { | |
return objectifier(name.split('.'), create, context); | |
}, | |
exists: function(name, context) { | |
return this.get(name, false, context) !== undefined; | |
} | |
}; | |
})(); |
Author
tomnagengast
commented
Aug 9, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment