Skip to content

Instantly share code, notes, and snippets.

@Williammer
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save Williammer/6781a687850fb91a00b1 to your computer and use it in GitHub Desktop.

Select an option

Save Williammer/6781a687850fb91a00b1 to your computer and use it in GitHub Desktop.
jsPatterns.constantFactory.js
var constant = (function () {
var constants = {},
ownProp = Object.prototype.hasOwnProperty,
allowed = {
string: 1,
number: 1,
boolean: 1
},
prefix = (Math.random() + "_").slice(2);
return {
set: function (name, value) {
if (this.isDefined(name)) {
return false;
}
if (!ownProp.call(allowed, typeof value)) {
return false;
}
constants[prefix + name] = value;
return true;
},
isDefined: function (name) {
return ownProp.call(constants, prefix + name);
},
get: function (name) {
if (this.isDefined(name)) {
return constants[prefix + name];
}
return null;
}
};
}());
// check if defined
constant.isDefined("maxwidth"); // false
// define
constant.set("maxwidth", 480); // true
// check again
constant.isDefined("maxwidth"); // true
// attempt to redefine
constant.set("maxwidth", 320); // false
// is the value still intact?
constant.get("maxwidth"); // 480
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment