Skip to content

Instantly share code, notes, and snippets.

@cramhead
Last active July 28, 2021 21:08
Show Gist options
  • Save cramhead/4a6fcc4206763404cab95311f7cea654 to your computer and use it in GitHub Desktop.
Save cramhead/4a6fcc4206763404cab95311f7cea654 to your computer and use it in GitHub Desktop.
JS/TS Snippets
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))`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment