Skip to content

Commit

Permalink
fix: filter recursively
Browse files Browse the repository at this point in the history
  • Loading branch information
slikts committed Feb 22, 2020
1 parent e87ed21 commit 8714127
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
12 changes: 5 additions & 7 deletions src/DeepCompositeSymbol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,17 @@ import { isObject } from './helpers';
* an object's entries (key-value pairs).
*/
// tslint:disable-next-line: variable-name
const DeepCompositeSymbol = ((object: any, keyFilter?: (key: string) => boolean) => {
const entries = keyFilter
? Object.entries(object).filter(entry => keyFilter(entry[0]))
: Object.entries(object);
const DeepCompositeSymbol = ((object: any, filter?: (entry: [string, any]) => boolean) => {
const entries = filter ? Object.entries(object).filter(filter) : Object.entries(object);
// Recursively replace non-tuple object values with tuples
entries.forEach(update);
entries.forEach(x => update(x, filter));
return Tuple.unsafeSymbol(...flatten(entries));
}) as any;

const update = (entry: any) => {
const update = (entry: any, filter?: any) => {
const v = entry[1];
if (isObject(v) && !(v instanceof Tuple)) {
entry[1] = DeepCompositeSymbol(v);
entry[1] = DeepCompositeSymbol(v, filter);
}
};

Expand Down
10 changes: 9 additions & 1 deletion test/DeepCompositeSymbol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,15 @@ describe(DeepCompositeSymbol.name, () => {
it('allows filtering by key', () => {
const o1 = { a: { c: 1 }, b: 2, _d: 3 };
const o2 = { ...o1, _d: 4 };
const filter = (key: string) => !key.startsWith('_');
const filter = ([key]: [string, any]) => !key.startsWith('_');
expect(DeepCompositeSymbol(o1, filter)).toBe(DeepCompositeSymbol(o2, filter));
expect(DeepCompositeSymbol(o1)).not.toBe(DeepCompositeSymbol(o2));
});

it('allows filtering by key recursively', () => {
const o1 = { a: { c: 1 }, b: 2, _d: 3 };
const o2 = { ...o1, a: { ...o1.a, _e: 4 } };
const filter = ([key]: [string, any]) => !key.startsWith('_');
expect(DeepCompositeSymbol(o1, filter)).toBe(DeepCompositeSymbol(o2, filter));
expect(DeepCompositeSymbol(o1)).not.toBe(DeepCompositeSymbol(o2));
});
Expand Down

0 comments on commit 8714127

Please sign in to comment.