Skip to content

Instantly share code, notes, and snippets.

@Ethan-Arrowood
Created November 22, 2017 05:20
Show Gist options
  • Save Ethan-Arrowood/a37773f236a6e5690d6275e01c9b65db to your computer and use it in GitHub Desktop.
Save Ethan-Arrowood/a37773f236a6e5690d6275e01c9b65db to your computer and use it in GitHub Desktop.
Adds a very simple history tracking feature to javascript objects.
var moment = require('moment');
function createHistoryObj(id, obj) {
return {
id,
...obj,
removed: false,
history: {
[moment().valueOf()]: { ...obj, change: "created" }
},
editObj: function(change, newVals) {
if ( change !== "edit" && change !== "remove" )
throw new Error(`Operation: ${change} invalid for Obj.testObj()`);
const { id, history, editObj, ...obj } = this; // obj contains tracked values
this.removed = change === "remove"; // if we are removing the test toggle removed
this.history[moment().valueOf()] = { ...obj,
change: change === "edit" ? "edited" : "removed" }; // grammarize change
if ( change === "edit" ) {
Object.keys(newVals).forEach((v, i) => {
if (this[v] === undefined)
throw new Error(`Property: ${v} does not exist in ${this.id}`);
this[v] = newVals[v];
});
} // no need to update object if we are 'removing' it
},
log: function() {
console.log(this);
console.log("");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment