Skip to content

Instantly share code, notes, and snippets.

@nathanjsharpe
Created October 29, 2015 19:22
Show Gist options
  • Save nathanjsharpe/f48b10f9010051f03344 to your computer and use it in GitHub Desktop.
Save nathanjsharpe/f48b10f9010051f03344 to your computer and use it in GitHub Desktop.
Merge and sync
// assets param is either a plain js object or an array of plain js objects
_merge(assets) {
// If parameter is a single object, make it an array
assets = Array.isArray(assets) ? assets : [assets];
// From object(s), create an ordered map of id => record
let newAssets = new OrderedMap(assets.map(asset => [asset.id, new Asset(asset)]));
// Merge in new assets, keeping old if new is equal (same values) to preserve reference equality
this._assets = this._assets.mergeWith((prev, next) => prev.equals(next) ? prev : next, newAssets);
// Return updated list of assets as well as new assets to enable sync
return { currentAssets: this._assets, newAssets };
}
_sync(assets) {
let { currentAssets, newAssets } = this._merge(assets);
// Remove assets in updated list that are not in old list, i.e., remove assets that have been deleted
return this._assets = currentAssets.filter(asset => newAssets.has(asset.id));
}
//...
case ActionTypes.ASSET_RECEIVE_ALL:
assetStore._sync(action.data);
assetStore.emitChange();
break;
case ActionTypes.ASSET_RECEIVE_CREATED:
case ActionTypes.ASSET_RECEIVE_UPDATED:
assetStore._merge(action.data);
assetStore.emitChange();
break;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment