Skip to content

Instantly share code, notes, and snippets.

@mhakes
Created May 12, 2017 01:48
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 mhakes/444f3ab6112631eed64a7ab9f79deb6c to your computer and use it in GitHub Desktop.
Save mhakes/444f3ab6112631eed64a7ab9f79deb6c to your computer and use it in GitHub Desktop.
Track changes to an object (very useful in form change tracking)
/* jshint esnext: true */
/* global _ */
/* this version leverages _ lodash - oh Lord, stuck in lodash again */
const formatData = thing => {
if (_.isNil(thing)) {
return thing;
}
if (_.isEmpty(thing)) {
return thing;
}
if (_.isString(thing)) {
if (_.isNaN(_.toNumber(thing))) {
return thing;
}
let n = _.toNumber(thing);
if (thing.includes(".")) {
return n;
}
// prevent zip codes etc from dropping the '0'
if (thing.length > 1 && thing.startsWith("0")) {
return thing;
}
return n;
}
if (_.isPlainObject(thing)) {
_.each(thing, function(v, k) {
thing[k] = formatData(v);
});
} else if (_.isArray(thing)) {
_.each(thing, function(v, i) {
thing[i] = formatData(v);
});
} else if (_.isMap(thing)) {
thing.forEach(function(value, key) {
thing.set(key, formatData(value));
});
}
return thing;
};
_.mixin({
formatData: formatData
});
const Mirror = (original = Object.create(null)) => {
let cache = new Map(Object.entries(_.formatData(original)));
const getCache = () => {
let x = {};
cache.forEach(function(value, key) {
x[key] = value;
});
return x;
};
const api = {
reflect(addToCache = true) {
let changed = Object.create(null);
const everything = getCache();
for (const [key, value] of Object.entries(original)) {
if (_.isNil(everything[key])) {
changed[key] = value;
} else if (!_.isEqual(original[key], everything[key])) {
changed[key] = value;
}
}
api.changed = changed;
if (_.isEmpty(changed)) {
return changed;
}
if (addToCache) {
cache = new Map(Object.entries(_.formatData(original)));
}
return changed;
}
};
return api;
};
/*
example:
let tracker = {
user_id: 8675309
};
let m = Mirror(tracker);
tracker.email = 'doesitmatter@whoever.com';
tracker.password = 'WeakSauce';
let changed = m.reflect(); //
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment