[gjs: 1/3] Closes: #469 ; added check for circular referencing when printing out objects




commit a571f4cc705fbd94068e7ecbfe7b4ea818c70c3d
Author: Nasah Kuma <nasahnash19 gmail com>
Date:   Fri Mar 18 23:38:54 2022 +0100

    Closes: #469 ;added check for circular referencing when printing out objects

 modules/script/_bootstrap/default.js | 24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)
---
diff --git a/modules/script/_bootstrap/default.js b/modules/script/_bootstrap/default.js
index e5953bf34..8c211a5ac 100644
--- a/modules/script/_bootstrap/default.js
+++ b/modules/script/_bootstrap/default.js
@@ -24,9 +24,10 @@
     }
 
     function prettyPrint(value) {
+        const printedObjects = new WeakSet();
         switch (typeof value) {
         case 'object':
-            return formatObject(value);
+            return formatObject(value, printedObjects);
         case 'function':
             return formatFunction(value);
         default:
@@ -34,9 +35,11 @@
         }
     }
 
-    function formatObject(obj) {
+    function formatObject(obj, printedObjects) {
+        printedObjects.add(obj);
         if (Array.isArray(obj))
-            return formatArray(obj).toString();
+            return formatArray(obj, printedObjects).toString();
+
         if (obj instanceof Date)
             return formatDate(obj);
 
@@ -44,7 +47,10 @@
         for (const [key, value] of Object.entries(obj)) {
             switch (typeof value) {
             case 'object':
-                formattedObject.push(`${key}: ${formatObject(value)}`);
+                if (printedObjects.has(value))
+                    formattedObject.push(`${key}: [Circular]`);
+                else
+                    formattedObject.push(`${key}: ${formatObject(value, printedObjects)}`);
                 break;
             case 'function':
                 formattedObject.push(`${key}: ${formatFunction(value)}`);
@@ -60,10 +66,14 @@
         return `{ ${formattedObject.join(', ')} }`;
     }
 
-    function formatArray(arr) {
+    function formatArray(arr, printedObjects) {
         const formattedArray = [];
-        for (const [key, value] of arr.entries())
-            formattedArray[key] = prettyPrint(value);
+        for (const [key, value] of arr.entries()) {
+            if (printedObjects.has(value))
+                formattedArray[key] = '[Circular]';
+            else
+                formattedArray[key] = prettyPrint(value);
+        }
         return `[${formattedArray.join(', ')}]`;
     }
 


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]