much more efficient

This commit is contained in:
Matt Hill
2022-09-14 09:27:30 -06:00
parent 74c01eb5db
commit 64b8d8567a

View File

@@ -111,38 +111,24 @@ export class PatchDB<T extends { [key: string]: any }> {
watch$(...args: (string | number)[]): Observable<any> { watch$(...args: (string | number)[]): Observable<any> {
const path = `/${args.join('/')}` const path = `/${args.join('/')}`
return new Observable(subscriber => { if (!this.watchedNodes[path]) {
const data = this.cache$.value.data const data = this.cache$.value.data
const value = getValueByPointer(data, path) const value = getValueByPointer(data, path)
const source = this.watchedNodes[path] || new BehaviorSubject(value) this.watchedNodes[path] = new BehaviorSubject(value)
const subscription = source.subscribe(subscriber) }
this.watchedNodes[path] = source return this.watchedNodes[path]
this.updateWatchedNode(path, data)
return () => {
subscription.unsubscribe()
if (!source.observed) {
source.complete()
delete this.watchedNodes[path]
}
}
})
} }
proccessUpdates(updates: Update<T>[], cache: DBCache<T>) { proccessUpdates(updates: Update<T>[], cache: DBCache<T>) {
updates.forEach(update => { updates.forEach(update => {
if (update.id <= cache.sequence) return
if (this.isRevision(update)) { if (this.isRevision(update)) {
if (update.id > cache.sequence + 1) { const expected = cache.sequence + 1
console.error( if (update.id < expected) return
`Received futuristic revision. Expected ${ if (update.id > expected) {
cache.sequence + 1 return console.error(
}, got ${update.id}`, `Received futuristic revision. Expected ${expected}, got ${update.id}`,
) )
return
} }
this.handleRevision(update, cache) this.handleRevision(update, cache)
} else { } else {
@@ -154,22 +140,25 @@ export class PatchDB<T extends { [key: string]: any }> {
} }
private handleRevision(revision: Revision, cache: DBCache<T>): void { private handleRevision(revision: Revision, cache: DBCache<T>): void {
// apply opperations
revision.patch.forEach(op => { revision.patch.forEach(op => {
applyOperation(cache, op) applyOperation(cache, op)
this.updateWatchedNodes(op.path, cache.data) })
// update watched nodes
revision.patch.forEach(op => {
Object.keys(this.watchedNodes).forEach(watchedPath => {
const revisionPath = op.path
if (revisionPath.includes(watchedPath)) {
this.updateWatchedNode(watchedPath, cache.data)
}
})
}) })
} }
private handleDump(dump: Dump<T>, cache: DBCache<T>): void { private handleDump(dump: Dump<T>, cache: DBCache<T>): void {
cache.data = { ...dump.value } cache.data = { ...dump.value }
this.updateWatchedNodes('', cache.data)
}
private updateWatchedNodes(revisionPath: string, data: T) {
Object.keys(this.watchedNodes).forEach(path => { Object.keys(this.watchedNodes).forEach(path => {
if (path.includes(revisionPath) || revisionPath.includes(path)) { this.updateWatchedNode(path, cache.data)
this.updateWatchedNode(path, data)
}
}) })
} }