Created
November 22, 2017 05:20
-
-
Save Ethan-Arrowood/a37773f236a6e5690d6275e01c9b65db to your computer and use it in GitHub Desktop.
Adds a very simple history tracking feature to javascript objects.
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
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