Skip to content

Commit

Permalink
Fix applying referential equality inside maps and sets (#221)
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelcollabai authored Jan 16, 2023
1 parent 7fec2d9 commit 22e8cd5
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/accessDeep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,27 @@ function validatePath(path: (string | number)[]) {
export const getDeep = (object: object, path: (string | number)[]): object => {
validatePath(path);

path.forEach(key => {
object = (object as any)[key];
});
for (let i = 0; i < path.length; i++) {
const key = path[i];
if (isSet(object)) {
object = getNthKey(object, +key);
} else if (isMap(object)) {
const row = +key;
const type = +path[++i] === 0 ? 'key' : 'value';

const keyOfRow = getNthKey(object, row);
switch (type) {
case 'key':
object = keyOfRow;
break;
case 'value':
object = object.get(keyOfRow);
break;
}
} else {
object = (object as any)[key];
}
}

return object;
};
Expand Down
33 changes: 33 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,39 @@ describe('stringify & parse', () => {
},
},

'works for referentially equal values in different maps and sets': {
input: () => {
const user = { id: 2 };

return {
workspaces: new Map([
[1, { users: new Set([user]) }],
[2, { users: new Set([user]) }],
]),
};
},
output: {
workspaces: [
[1, { users: [{ id: 2 }] }],
[2, { users: [{ id: 2 }] }],
],
},
outputAnnotations: {
values: {
workspaces: [
'map',
{
'0.1.users': ['set'],
'1.1.users': ['set'],
},
],
},
referentialEqualities: {
'workspaces.0.1.users.0': ['workspaces.1.1.users.0'],
},
},
},

'works for symbols': {
skipOnNode10: true,
input: () => {
Expand Down

0 comments on commit 22e8cd5

Please sign in to comment.