Last active
July 28, 2021 21:08
-
-
Save cramhead/4a6fcc4206763404cab95311f7cea654 to your computer and use it in GitHub Desktop.
JS/TS Snippets
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
Prints nested arrays as one string. Handy for Quokka.js | |
``` | |
function printNestedArray(arr, depth = 0) { | |
let result = '' | |
const indent = ' '.repeat(depth)); | |
if (Array.isArray(arr)) { | |
result = result + `\n${indent}[` | |
for (const item of arr) { | |
result = result + indent + printNestedArray(item, depth + 1) | |
} | |
result = result + `\n${indent}]` | |
} else { | |
result = result + `\n${indent}${depth}: ${arr.value}` | |
} | |
return result; | |
} | |
``` | |
// safely handles circular references | |
``` | |
const safeStringify = (obj, indent = 2) => { | |
let cache = []; | |
const retVal = JSON.stringify( | |
obj, | |
(key, value) => | |
typeof value === 'object' && value !== null | |
? cache.includes(value) | |
? undefined // Duplicate reference found, discard key | |
: cache.push(value) && value // Store value in our collection | |
: value, | |
indent | |
); | |
cache = null; | |
return retVal; | |
}; | |
``` | |
// Example: | |
`console.log('options', safeStringify(options))` |
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
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment