Skip to content

Commit

Permalink
fix: handle slashes better when decycling (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
pytlesk4 authored May 25, 2021
1 parent 867da5b commit 98c58f9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 11 deletions.
8 changes: 4 additions & 4 deletions src/__tests__/decycle.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,19 @@ describe('decycle', () => {

const obj = {
paths: {
'/circle': {
'/circle/foo': {
obj2: {},
},
},
};
obj.paths['/circle'].obj2 = obj2;
obj.paths['/circle/foo'].obj2 = obj2;

expect(decycle(obj)).toEqual({
paths: {
'/circle': {
'/circle/foo': {
obj2: {
circle: {
$ref: '#/paths/~1circle/obj2',
$ref: '#/paths/~1circle~1foo/obj2',
},
},
},
Expand Down
14 changes: 7 additions & 7 deletions src/decycle.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { isPlainObject } from './_utils';
import { encodePointer } from './encodePointer';
import { pathToPointer } from './pathToPointer';

export const decycle = (obj: unknown, replacer?: (value: any) => any) => {
const objs = new WeakMap<object, string>();
return (function derez(value: any, path: string) {
return (function derez(value: any, path: string[]) {
// The new object or array
let curObj: any;

Expand All @@ -15,22 +15,22 @@ export const decycle = (obj: unknown, replacer?: (value: any) => any) => {
const oldPath = objs.get(value);
// If the value is an object or array, look to see if we have already
// encountered it. If so, return a {"$ref":PATH} object.
if (oldPath) return { $ref: encodePointer(oldPath) };
if (oldPath) return { $ref: oldPath };

objs.set(value, path);
objs.set(value, pathToPointer(path));
// If it is an array, replicate the array.
if (Array.isArray(value)) {
curObj = value.map((element, i) => derez(element, `${path}/${i}`));
curObj = value.map((element, i) => derez(element, [...path, String(i)]));
} else {
// It is an object, replicate the object.
curObj = {};
Object.keys(value).forEach(name => {
curObj[name] = derez(value[name], `${path}/${name}`);
curObj[name] = derez(value[name], [...path, name]);
});
}
objs.delete(value);
return curObj;
}
return value;
})(obj, '#');
})(obj, []);
};

0 comments on commit 98c58f9

Please sign in to comment.