Skip to content

Instantly share code, notes, and snippets.

@ulfryk
Created February 2, 2017 07:47
Show Gist options
  • Save ulfryk/3af9a803cc110454733bf91fd439626e to your computer and use it in GitHub Desktop.
Save ulfryk/3af9a803cc110454733bf91fd439626e to your computer and use it in GitHub Desktop.
import { Map } from 'immutable';
import { IResource, IResourceId } from 'dto/resource';
import { optionalFindIndex } from '../common/utility/optional-find-index';
class IndexedCollection<R extends IResource<R>> {
constructor(
private readonly items: R[],
private readonly indexed: Map<IResourceId<R>, R>,
) {}
public set(id: IResourceId<R>, item: R) {
return new IndexedCollection(
optionalFindIndex(this.items, ({ id }) => id === item.id)
.cata(
() => this.items.concat(item),
index => this.items
.slice(0, index - 1)
.concat(item)
.concat(this.items.slice(index))),
this.indexed.set(id, item),
);
}
public update(id: IResourceId<R>, updater: (item: R) => R) {
return new IndexedCollection(
this.items.map(item => item.id === id ? updater(item) : item),
this.indexed.has(id) ? this.indexed.update(id, updater) : this.indexed,
);
}
public feed(items: R[]) {
return new IndexedCollection(
items.slice(),
items.reduce((indexed, item) => indexed.set(item.id, item), this.indexed),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment