Created
May 27, 2019 00:20
-
-
Save surrealist/2c06db8feef3e40540ca7d28c58be4cf to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| JSON.stringifyOnce = function(obj, replacer, indent){ | |
| var printedObjects = []; | |
| var printedObjectKeys = []; | |
| function printOnceReplacer(key, value){ | |
| if ( printedObjects.length > 2000){ // browsers will not print more than 20K, I don't see the point to allow 2K.. algorithm will not be fast anyway if we have too many objects | |
| return 'object too long'; | |
| } | |
| var printedObjIndex = false; | |
| printedObjects.forEach(function(obj, index){ | |
| if(obj===value){ | |
| printedObjIndex = index; | |
| } | |
| }); | |
| if ( key == ''){ //root element | |
| printedObjects.push(obj); | |
| printedObjectKeys.push("root"); | |
| return value; | |
| } | |
| else if(printedObjIndex+"" != "false" && typeof(value)=="object"){ | |
| if ( printedObjectKeys[printedObjIndex] == "root"){ | |
| return "(pointer to root)"; | |
| }else{ | |
| return "(see " + ((!!value && !!value.constructor) ? value.constructor.name.toLowerCase() : typeof(value)) + " with key " + printedObjectKeys[printedObjIndex] + ")"; | |
| } | |
| }else{ | |
| var qualifiedKey = key || "(empty key)"; | |
| printedObjects.push(value); | |
| printedObjectKeys.push(qualifiedKey); | |
| if(replacer){ | |
| return replacer(key, value); | |
| }else{ | |
| return value; | |
| } | |
| } | |
| } | |
| return JSON.stringify(obj, printOnceReplacer, indent); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment