Skip to content

Instantly share code, notes, and snippets.

@netpoetica
Last active December 21, 2015 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save netpoetica/6259995 to your computer and use it in GitHub Desktop.
Save netpoetica/6259995 to your computer and use it in GitHub Desktop.
Clevar constructs an accessor function that retains its own History Store and keeps the value absolutely private. Neat utility for tracking history of a variable over time.
var Clevar = function(value){
// Constructs an accessor function that retains its own History Store.
var _this = this;
var _history = []; // Indexable history (newest to oldest)
// Define static objects, only the first time Clevar is run.
Clevar.Record = Clevar.Record || function(value){
this.created = new Date();
this.value = value;
};
Clevar.Record.prototype.getFormatted = Clevar.Record.prototype.getFormatted || function(next){
return 'Value was ' + this.value + ', created at ' + this.created.toUTCString() + (next ? ' and changed at ' + next.created.toUTCString() : '');
};
var Record = Clevar.Record; // Reference to static object - reduce scope lookup.
var _current = value ? new Record(value) : new Record(null); // Current value
return function(value, index/* Only for use with exploring history */){
// Value should be able to be 0 or null and go on record.
if(value !== undefined){ // SET
// User is requesting history of Clevar instance. If index provided does not exist, returns all records for user to sort through.
if(value === '__history'){ return (index !== undefined && typeof _history[index] === 'object') ? _history[index].getFormatted(typeof _history[index + 1] === 'object' ? _history[index + 1] : null) : _history; }
// Need to perform a deep clone on objects, otherwise passed by reference. Save for a more clevar solution.
// If you have jQuery, prototype, or anything with an extend/deep clone function, this would be the place to use it.
if(_current.value instanceof Object && typeof $.extend === 'function'){
_history.push($.extend({}, _current));
} else {
// Otherwise, no deep clone.
_history.push(_current);
}
// Set new current value.
_current = new Record(value);
} else { // GET
return _current.value;
}
}
};
/*
USAGE:
// Declare.
var a = new Clevar('hello');
// Set.
a('world');
a(20);
// Get.
a(); // -> world
// Full history.
a('__history'); // -> [Record, Record, Record]
// History by index.
a('__history', 2); // -> Informative string.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment