Skip to content

Commit

Permalink
feat(app-state): spreadObjectStore$() handles null and undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
ersimont committed Nov 23, 2020
1 parent 7d19f47 commit c15b653
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ describe('spreadArrayStore$()', () => {
arrayStore.set([1]);
expect(emitted.length).toBe(1);

arrayStore.delete();
arrayStore.set(null);
expect(emitted.length).toBe(0);
});
});
18 changes: 18 additions & 0 deletions projects/app-state/src/lib/utils/spread-object-store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,22 @@ describe('spreadObjectStore$()', () => {
store.set({ b: 6 });
expect(lastEmit![0]).toBe(previousEmit![1]);
});

it('treats null and undefined as empty objects', () => {
interface State {
object?: Record<string, number> | null;
}
const objectStore = new RootStore<State>({})('object');
let emitted!: Array<Store<number>>;
spreadObjectStore$(objectStore).subscribe((stores) => {
emitted = stores;
});
expect(emitted.length).toBe(0);

objectStore.set({ a: 1 });
expect(emitted.length).toBe(1);

objectStore.set(null);
expect(emitted.length).toBe(0);
});
});
4 changes: 2 additions & 2 deletions projects/app-state/src/lib/utils/spread-object-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import { Store } from '../index';
* ```
*/
export function spreadObjectStore$<T extends object>(
source: Store<T>,
source: Store<T | null | undefined>,
): Observable<Array<Store<T[keyof T]>>> {
let lastKeySet: Set<string | keyof T> | undefined;
return source.$.pipe(
Expand All @@ -47,7 +47,7 @@ export function spreadObjectStore$<T extends object>(
}),
mapAndCacheObjectElements(
(_value, key) => key,
(_value, key) => source(key as keyof T),
(_value, key) => (source as Store<T>)(key as keyof T),
),
);
}
15 changes: 15 additions & 0 deletions projects/app-state/src/typing-tests/spead-object-store.dts-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { spreadObjectStore$, Store } from '../public-api';

declare const object: Store<Record<string, number>>;
declare const objectOrNull: Store<Record<string, number> | null>;
declare const objectOrUndefined: Store<Record<string, number> | undefined>;
declare const objectOrNil: Store<Record<string, number> | null | undefined>;

// $ExpectType Observable<Store<number>[]>
spreadObjectStore$(object);
// $ExpectType Observable<Store<number>[]>
spreadObjectStore$(objectOrNull);
// $ExpectType Observable<Store<number>[]>
spreadObjectStore$(objectOrUndefined);
// $ExpectType Observable<Store<number>[]>
spreadObjectStore$(objectOrNil);

0 comments on commit c15b653

Please sign in to comment.