-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #56 from dieuhd/fix/debug_mode
fix: exception bug for debug mode
- Loading branch information
Showing
3 changed files
with
54 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
const isArray = (value: any) => Array.isArray(value); | ||
|
||
const isObject = (value: any) => | ||
Object.prototype.toString.call(value).slice(8, -1) === "Object"; | ||
|
||
const validate = (value: any) => { | ||
if (typeof value === "undefined") { | ||
throw new Error("This method requires one parameter"); | ||
} | ||
|
||
if (!isArray(value) && !isObject(value)) { | ||
throw new TypeError("This method only accepts arrays and objects"); | ||
} | ||
}; | ||
|
||
const findRef = (ref: any, visitedRefs: any) => | ||
Object.keys(visitedRefs).find((key) => visitedRefs[key] === ref); | ||
|
||
export const decycle = (arg: any) => { | ||
validate(arg); | ||
|
||
const visitedRefs: any = {}; | ||
|
||
const recurs = (value: any, path = "$") => { | ||
const ref = findRef(value, visitedRefs); | ||
if (ref) { | ||
return { $ref: ref }; | ||
} | ||
if (isArray(value) || isObject(value)) { | ||
visitedRefs[path] = value; | ||
|
||
if (isArray(value)) { | ||
return value.map((elem: any, i: any) => recurs(elem, `${path}[${i}]`)); | ||
} | ||
|
||
return Object.keys(value).reduce((accum: any, key: any) => { | ||
accum[key] = recurs(value[key], `${path}.${key}`); | ||
|
||
return accum; | ||
}, {}); | ||
} | ||
return value; | ||
}; | ||
return recurs(arg); | ||
}; |