Skip to content

Instantly share code, notes, and snippets.

@vladimir-ivanov
Last active February 3, 2022 09:03
Show Gist options
  • Save vladimir-ivanov/cab36a3d3fbdfb954be22bd0fcce38d1 to your computer and use it in GitHub Desktop.
Save vladimir-ivanov/cab36a3d3fbdfb954be22bd0fcce38d1 to your computer and use it in GitHub Desktop.
transactional list cache
interface WithId {
id: string | number;
}
type Transaction<T extends WithId = WithId> = T[];
export class TransactionalCache<T extends WithId = WithId> {
private remove: T[];
private update: T[];
private add: T[];
updateTransactions = (transactions: Transaction<T>, callback: Function) => {
this.removeItems(transactions);
this.addItems(transactions);
this.updateItems(transactions);
callback();
};
flush = () => {
this.remove = [];
this.add = [];
this.update = [];
};
getTransactions = () => ({add, update, remove});
private removeItems = (toRemove: T[]) => {
const toIds = toRemove.map(({ id }) => id);
this.remove = [...this.remove.filter(({ id }) => {
return toIds.indexOf(id) === -1;
}), ...toRemove];
this.add = [...this.add.filter(({ id }) => {
return toRemove.indexOf(id) === -1;
});
this.update = this.update.filter(({ id }) => {
return toRemove.indexOf(id) === -1;
});
};
private addItems = (toAdd: T[]) => {
const toAddIds = toAdd.map(({ id }) => id);
this.add = [...this.add.filter(({ id }) => {
return toAddIds.indexOf(id) === -1;
}), ...toAdd];
};
private updateItems = (toUpdate: T[]) => {
const toIds = toUpdate.map(({ id }) => id);
this.update = [...this.update.filter(({ id }) => {
return toIds.indexOf(id) === -1;
}), ...toUpdate];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment