Skip to content

Instantly share code, notes, and snippets.

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

  • Save TGOlson/44f50441846b5847bde0 to your computer and use it in GitHub Desktop.

Select an option

Save TGOlson/44f50441846b5847bde0 to your computer and use it in GitHub Desktop.
Simple JavaScript Constants
/*
* JavaScript Constant
*
* Create constants via Api
* Retreive values from window/global without Api
*
* This will work in both browsers and node
*
* Enforces standard rules:
* Requires uppercase naming conventions
* Does not allow right hand assignment once constant is set
*/
var global = this;
function constant(name, value) {
if(!isUppercase(name)) {
constant._error('Illegal constant name.', name);
}
if(isGloballyDefined(name)) {
constant._error('Constant already defined.', name);
}
constant._define(name, value);
}
constant._error = function(msg, name) {
throw new Error('CONSTANT ERROR: ' + msg + ' For constant: ' + name);
};
constant._define = function(name, value) {
Object.defineProperty(global, name, {
get: function() {
return value;
},
set: function(val) {
constant._error('Illegal right hand assignment.', name);
}
});
};
constant._remove = function(name) {
if(isGloballyDefined(name)) {
global[name] = undefined;
} else {
constant._error('Cannot delete undefined constant.', name);
}
};
function isUppercase(value) {
return value === value.toUpperCase();
}
function isGloballyDefined(value) {
return !isUndefined(global[value]);
}
function isUndefined(value) {
return value === undefined;
}
constant('PERSON', 'Tyler');
constant('AGE', 26);
console.log(PERSON);
// => Tyler
console.log(AGE);
// => 26
PERSON = 'Steve';
// => Error: Illegal right hand assignment for constant: PERSON
constant('Person', 'Tyler');
// => Illegal constant name - must be uppercase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment