Skip to content

Instantly share code, notes, and snippets.

@tomnagengast
Last active August 9, 2017 19:09
Show Gist options
  • Save tomnagengast/2d12f1c02a893c744d03e2996f004416 to your computer and use it in GitHub Desktop.
Save tomnagengast/2d12f1c02a893c744d03e2996f004416 to your computer and use it in GitHub Desktop.
/**
* 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;
}
};
})();
@tomnagengast
Copy link
Author

// Creates my.namespace.MyClass
Objectifier.set('my.namespace.MyClass', {
	name: 'David'
});
// my.namespace.MyClass.name = 'David'

// Creates some.existing.objecto.my.namespace.MyClass
Objectifier.set('my.namespace.MyClass', {
	name: 'David'
}, some.existing.objecto); // Has to be an existing object

// Get an object
Objectifier.get('my.namespace.MyClassToo');

// Try to find an object, create it if it doesn't exist
Objectifier.get('my.namespace.MyClassThree', true);

// Check for existence
Objectifier.exists('my.namespace.MyClassToo'); // returns TRUE or FALSE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment