Skip to content

Instantly share code, notes, and snippets.

@gtzilla
Last active May 2, 2016 12:04
Show Gist options
  • Save gtzilla/a563a5728491dcc3f88cf806f3857507 to your computer and use it in GitHub Desktop.
Save gtzilla/a563a5728491dcc3f88cf806f3857507 to your computer and use it in GitHub Desktop.
JavaScript closure state manager for a single argument, with support for default state initialization value. A JavaScript private variables method.
;(function(window) {
'use strict';
/**
filename: helpers.js
author: gregory tomlinson
license: MIT
Be a "utility" helper method
file that is namespaced to 'helpers'
*/
/**
Be a "state" handler function
This closured state handler with built in get/set logic
can suffice in several scenarios
this avoids the obtuse 'get/set' syntax in favor
of a more business-rule friendly, declarative,
format
usages:
INIT: var myFncVar = helpers.closure_state({data:false}); // set default on init
SET: myFncVar({data:true});
GET: myFncVar();
Other examples:
function Point(cx, cy) {
this.x = helpers.closure_state(cx);
this.y = helpers.closure_state(cy);
return this;
}
var pt = new Point(10, 20);
pt.x();
// 10
pt.y();
// 20
var myarray = helpers.closure_state([]);
myarray().push("something")
myarray()
// ["something"]
*/
/**
@params {Array|Object|String|Numnber|ANY} state - a variable of any type.
sets default 'state'
*/
function closure_state(state) {
var STATE = state !== undefined ? state : null;
return function() {
if(arguments.length) {
STATE = arguments[0];
}
return STATE;
}
}
var helpers = window.helpers = {
closure_state:closure_state
}
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment