From afc87f3c5904274195d80868beae90a9dfa4e613 Mon Sep 17 00:00:00 2001 From: Florian Dold Date: Tue, 24 May 2016 00:28:24 +0200 Subject: [PATCH] implement flatMap operation for query streams --- lib/wallet/query.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/lib/wallet/query.ts b/lib/wallet/query.ts index 1e39fda0f..d5ec1fecc 100644 --- a/lib/wallet/query.ts +++ b/lib/wallet/query.ts @@ -38,6 +38,7 @@ export interface QueryStream { keyFn: (obj: any) => any): QueryStream<[T,S]>; filter(f: (any) => boolean): QueryStream; reduce(f: (v: T, acc: S) => S, start?: S): Promise; + flatMap(f: (T) => T[]): QueryStream; } @@ -68,6 +69,10 @@ abstract class QueryStreamBase implements QueryStream { this.root = root; } + flatMap(f: (T) => T[]): QueryStream { + return new QueryStreamFlatMap(this, f); + } + indexJoin(storeName: string, indexName: string, key: any): QueryStream<[T,S]> { @@ -117,6 +122,31 @@ class QueryStreamFilter extends QueryStreamBase { return; } if (this.filterFn(value)) { + f(false, value, tx); + } + }); + } +} + + +class QueryStreamFlatMap extends QueryStreamBase { + s: QueryStreamBase; + flatMapFn; + + constructor(s: QueryStreamBase, flatMapFn) { + super(s.root); + this.s = s; + this.flatMap = flatMapFn; + } + + subscribe(f) { + this.s.subscribe((isDone, value, tx) => { + if (isDone) { + f(true, undefined, tx); + return; + } + let values = this.flatMapFn(value); + for (let v in values) { f(false, value, tx) } });