-
-
Notifications
You must be signed in to change notification settings - Fork 126
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add ObservableGroupMap #245
Conversation
Logged output of the current "test":
|
1aba0df
to
eab2810
Compare
Looks cool! I'd take ObservableMap as basis, and make disposal explicit indeed :) For example through |
An ObservableGroupMap is constructed from a base IObservableArray and a `groupBy` function. It maps `groupBy` values to IObservableArrays of the items in the base array which have groupBy(item) == key The IObservableArrays are updated reactively when items in the base array are removed, changed or added. Updates are done without iterating through the base array (except once at the beginning)
Yeah, ObservableMap makes sense, because then you can observe for example
I've added some more tests and improved the documentation, I'll merge this in a couple of days if no one objects. |
An ObservableGroupMap is constructed from a base IObservableArray and a
groupBy
function.It maps
groupBy
values to IObservableArrays of the items in the base array which have groupBy(item) == keyThe IObservableArrays are updated reactively when items in the base array are removed, changed or added.
Updates are done without iterating through the base array (except once at the beginning)
This is a first draft to demonstrate the idea, if there's interest in adding it to mobx-utils, I will make it more robust and add proper tests.
My concrete usecase is basically what I've implemented at the bottom of the file:
If I have an array of time-intervals, and I want to calculate aggregate statistics about them (for example sums per day) the obvious solution has terrible performance:
... which has O(n²)
I can improve upon that by iterating once and building a map, and then I can improve even more, by only adjusting the output arrays when actually necessary, which is what this PR does.
I went through the docs carefully and didn't find anything for this usecase.
This partly covers mobxjs/mobx#166
Open issues:
Use plain Map or ObservableMap as base Map? (or configurable)ObservableMap as base makes most sense, because then ogm.keys() is observable, as well as for example(ogm.get(x) ?? []).length
to observe the number of items with a particular groupBy[ ] listen to onBecomeObserved /onBecomeUnobserved events or make dispose explicit? If the group-map only becomes unobserved for a short while, the overhead of disposing of all the listeners and recreating them could be significant.