Last active
August 29, 2015 13:58
-
-
Save andrewluetgers/9952161 to your computer and use it in GitHub Desktop.
seal and sealh: prototype chain used to create a projection of current object as original + changes, sealh stores a history of all changes from call to call
This file contains 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
// prototype chain used to create a projection of current object as original + changes | |
// the return object is always an instance of the provided object, changes form a change-set | |
// todo deal with deeply nested prototype chains | |
function seal(d) { | |
var x = _seal(d); | |
if (_.isObject(d)) { | |
_.each(d, function(v, k) { | |
if (d.hasOwnProperty(k) && _.isObject(v)) { | |
x[k] = seal(v); | |
} | |
}); | |
} | |
return x; | |
} | |
function f() {} | |
function _seal(d) { | |
f.prototype = d; | |
return new f(); | |
} | |
// todo find forks function | |
// any node showing up in more than one history is a fork | |
// can we use === ?? | |
// can use JSON.stringify on history to see just the changes across versions | |
var nodes = []; | |
var history = []; | |
function sealh(d) { | |
var idx = nodes.indexOf(d); | |
if (idx < 0) { | |
idx = nodes.push(d); | |
} | |
var h = history[idx] || []; | |
history[idx] = h; | |
h.push(d); | |
var s = seal(d); | |
nodes[idx] = s; | |
return s; | |
} | |
function changes(history) { | |
return _.map(history, function(h) { | |
var changes, hasChanges; | |
if (_.isArray(h)) { | |
changes = []; | |
} else { | |
changes = {}; | |
} | |
_.each(h, function(v, k) { | |
if (h.hasOwnProperty(k)) { | |
hasChanges = true; | |
changes[k] = v; | |
} | |
}); | |
return changes; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment