Skip to content

Instantly share code, notes, and snippets.

@serby
Created May 23, 2012 14:19
Show Gist options
  • Save serby/2775473 to your computer and use it in GitHub Desktop.
Save serby/2775473 to your computer and use it in GitHub Desktop.
JavaScript implementation of set synchronisation. Bound by memory but minimizes database read writes.
var _ = require('underscore')
, a = {
1: { id: '1', name: 'a' },
2: { id: '2', name: 'b' },
3: { id: '3', name: 'c' }
}
, b = {
2: { id: '2', name: 'b1' },
3: { id: '3', name: 'c2' },
4: { id: '4', name: 'd' }
};
function getId(item) {
return item.id;
}
function isDifferent(first, second) {
return Object.keys(first).some(function(key) {
return first[key] !== second[key];
});
}
function create(newObject) {
a[newObject.id] = newObject;
}
function update(id, newObject) {
a[id] = newObject;
}
function del(id) {
delete a[id];
}
function sync(a, b, getId, isDifferent, create, update, del) {
// Create sets
var aIds = _.pluck(a, 'id')
, bIds = _.pluck(b, 'id')
, c = _.difference(aIds, bIds)
, d = _.intersection(aIds, bIds)
, e = _.difference(bIds, d);
// Delete omitted items
c.forEach(del);
// Update only those that have changed
d.forEach(function(index) {
if (isDifferent(a[index], b[index])) {
//update.push(b[index]);
update(index, b[index]);
}
});
// Insert new items
e.forEach(function(index) {
create(b[index]);
});
}
sync(a, b, getId, isDifferent, create, update, del);
console.log(a);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment