Skip to content

Instantly share code, notes, and snippets.

@savelichalex
Last active March 26, 2018 13:18
Show Gist options
  • Save savelichalex/aedff395228896455ac79e660bb97942 to your computer and use it in GitHub Desktop.
Save savelichalex/aedff395228896455ac79e660bb97942 to your computer and use it in GitHub Desktop.
const NotifReconciler = new NotificationReconciler();
// add some notification to schedule
NotifReconciler.process([
new MyNotification({ date: "01/01/2018", message: "Hello World", id: 1 }),
new MyNotification({ date: "01/02/2018", message: "Hello World2", id: 2 }),
]);
// second notification not needed now
// it will cancel only second
NotifReconciler.process([
new MyNotification({ date: "01/01/2018", message: "Hello World", id: 1 }),
]);
// simple array diff algo with O(2m+n) complexity
const arraysDiff = (first, second, key) => {
const keysInFirst = first.reduce((acc, item) => {
if (item == null) {
return acc;
}
const id = item[key];
acc[id] = item;
return acc;
}, {});
const added = second.reduce((acc, item) => {
if (item == null) {
return acc;
}
const id = item[key];
const isExist = keysInFirst[id];
if (isExist != null) {
keysInFirst[id] = null;
} else {
acc.push(item);
}
return acc;
}, []);
const removed = Object.keys(keysInFirst).reduce((acc, key) => {
const item = keysInFirst[key];
if (item == null) {
return acc;
}
acc.push(item);
return acc;
}, []);
return {
removed,
added,
};
};
export class NotificationReconciler {
savedNotifications: Array<Notification> = [];
static storageKey: string = 'Notifications';
private persistanceState: ReconcilerPersistanceState = ReconcilerPersistanceState.empty;
process(newNotifications: Array<Notification>): void {
const { removed, added } = arraysDiff(this.savedNotifications, newNotifications, 'id');
added.forEach((item: Notification) => {
if (item == null) {
return;
}
this.add(item);
});
removed.forEach(item => {
if (item == null) {
return;
}
this.remove(item);
});
this.saveNewNotifications(newNotifications);
}
private add(notification: Notification): void {
this.pushNotification.localNotificationSchedule({
date: notification.date,
message: notification.message,
userInfo: { id: notification.id },
});
}
private remove(notification: Notification): void {
this.pushNotification.cancelLocalNotifications({ id: notification.id });
}
private saveNewNotifications(notifications: Array<Notification>): void {
this.savedNotifications = notifications;
this.storage.setItem(
NotificationReconciler.storageKey,
JSON.stringify(notifications.filter(it => it != null).map(({ id }) => ({ id })))
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment