Skip to content

terotests/ObjectFork

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 

Repository files navigation

ObjectFork

Simple fork out from a plain JS Object - maintains the master object as immutable.

LIMITATIONS: Mutating a forked Array using Array functions like push is not possible

Usage;

    var myData = { x : 100, y : 200, 
        subObj : {
            name : "Subitem name"  
        },
        items : [
            { name : "first item"}
        ]};
    var forked = ObjectFork().fork( myData );
    
    // do something with forked data...
    
    ObjectFork().commit( myData );
    
        

Class ObjectFork

Class ObjectFork

The class has following internal singleton variables:

ObjectFork::commit(obj)

obj Forked object that should be committed back to it's source

// merge the object back to it's master object
if(obj.__master) {
    // anything that has changed...
    var me = this, original = obj.__master;
    
    Object.keys(obj).forEach(function(key) {
        if( (obj[key] instanceof Array) || (typeof(obj[key])=="object") ) {
            if(original[key]) return me.commit( obj[key] );     
            original[key] = obj[key];
        } else {
            original[key] = obj[key];
        }
    });    
}

ObjectFork::fork(obj)

obj object to fork, otherwise using the root object

var original = obj || this._root;

var forkClass = function() {};
forkClass.prototype = original;

var fork = new forkClass();
var me = this, _privateValues = {};
// loop all the keys of the original...
Object.keys(original).forEach(function(key) {
    if( (original[key] instanceof Array) || (typeof(original[key])=="object") ) {
        // 
        Object.defineProperty(fork, key, {
            enumerable: true,
            get: function() {
              if(_privateValues[key]) return _privateValues[key];
              if(!original[key]) return null;
              _privateValues[key] = me.fork(original[key]);
              return _privateValues[key];
            }, 
            set : function(value) {
                _privateValues[key] = value;
            }
        });         
    }
});

// define __master as a point where the for started
Object.defineProperty(fork, "__master", {
    enumerable: false,
    get: function() {
      return original;
    },
    set: function(value) {
      
    }
}); 
return fork;

ObjectFork::constructor( rootObject, options )

this._root = rootObject;

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published