Skip to content

Commit

Permalink
feat(DeepCompositeSymbol): add a shallow registry
Browse files Browse the repository at this point in the history
  • Loading branch information
slikts committed Feb 24, 2020
1 parent 1f8a59d commit 0ccc6e4
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
14 changes: 12 additions & 2 deletions src/DeepCompositeSymbol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,21 @@ const DeepCompositeSymbol = (object: any, filter?: (entry: [string, any]) => boo
return Tuple.unsafeSymbol(...flatten(entries));
};

export const shallow = Symbol('shallow');
export const shallowKey = Symbol('shallow');
export const shallowCache = new WeakSet<object>();
export const shallow = <A extends object>(a: A): A => {
shallowCache.add(a);
return a;
};

const update = (entry: [string, any], filter?: any) => {
const value = entry[1];
if (isObject(value) && !(value as any)[shallow] && !(value instanceof Tuple)) {
if (
isObject(value) &&
!(value as any)[shallowKey] &&
!(value instanceof Tuple) &&
!shallowCache.has(value)
) {
entry[1] = DeepCompositeSymbol(value, filter);
}
};
Expand Down
2 changes: 1 addition & 1 deletion src/tuplerone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import ValueObject from './ValueObject';

export { symbol as CompositeSymbol } from './Tuple';
export { memoize } from './memoize';
export { shallow } from './DeepCompositeSymbol';
export { shallowKey, shallow } from './DeepCompositeSymbol';

/**
* A tuple whose members are allowed to all be primitive,
Expand Down
12 changes: 10 additions & 2 deletions test/ValueObject.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ValueObject, shallow } from '../src/tuplerone';
import { ValueObject, shallowKey, shallow } from '../src/tuplerone';

describe(ValueObject.name, () => {
it('constructs', () => {
Expand Down Expand Up @@ -45,7 +45,15 @@ describe(ValueObject.name, () => {
const b = { a };
a.b = b;
expect(() => ValueObject(a)).toThrow();
a[shallow] = true;
a[shallowKey] = true;
expect(() => ValueObject(a)).not.toThrow();
});

it('can be short-circuited using a WeakSet registry', () => {
const a: any = {};
const b = { a };
a.b = b;
expect(() => ValueObject(a)).toThrow();
expect(() => ValueObject(shallow(a))).not.toThrow();
});
});

0 comments on commit 0ccc6e4

Please sign in to comment.