Last active
August 29, 2015 14:02
-
-
Save Williammer/6781a687850fb91a00b1 to your computer and use it in GitHub Desktop.
jsPatterns.constantFactory.js
This file contains hidden or 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
| 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