streamManager.tsx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. type Options = {
  2. /** Max number of items to keep at once */
  3. limit?: number;
  4. };
  5. /**
  6. * Minimal type shape for objects that can be managed inside StreamManager.
  7. */
  8. type IdShape = {
  9. id: string;
  10. };
  11. class StreamManager {
  12. private idList: string[] = [];
  13. private limit: number;
  14. private store: any;
  15. // TODO(dcramer): this should listen to changes on GroupStore and remove
  16. // items that are removed there
  17. // TODO(ts) Add better typing for store. Generally this is GroupStore, but it could be other things.
  18. constructor(store: any, options: Options = {}) {
  19. this.store = store;
  20. this.limit = options.limit || 100;
  21. }
  22. reset() {
  23. this.idList = [];
  24. }
  25. trim() {
  26. if (this.limit > this.idList.length) {
  27. return;
  28. }
  29. const excess = this.idList.splice(this.limit, this.idList.length - this.limit);
  30. this.store.remove(excess);
  31. }
  32. push(items: IdShape | IdShape[] = []) {
  33. items = Array.isArray(items) ? items : [items];
  34. if (items.length === 0) {
  35. return;
  36. }
  37. items = items.filter(item => item.hasOwnProperty('id'));
  38. const ids = items.map(item => item.id);
  39. this.idList = this.idList.filter(id => !ids.includes(id));
  40. this.idList = [...this.idList, ...ids];
  41. this.trim();
  42. this.store.add(items);
  43. }
  44. getAllItems() {
  45. return this.store
  46. .getAllItems()
  47. .slice()
  48. .sort((a, b) => this.idList.indexOf(a.id) - this.idList.indexOf(b.id));
  49. }
  50. unshift(items: IdShape | IdShape[] = []) {
  51. items = Array.isArray(items) ? items : [items];
  52. if (items.length === 0) {
  53. return;
  54. }
  55. const ids = items.map(item => item.id);
  56. this.idList = this.idList.filter(id => !ids.includes(id));
  57. this.idList = [...ids, ...this.idList];
  58. this.trim();
  59. this.store.add(items);
  60. }
  61. }
  62. export default StreamManager;