UNPKG

@mintlify/common

Version:

Commonly shared code within Mintlify

27 lines (26 loc) 948 B
import cloneDeepWith from 'lodash/cloneDeepWith.js'; export function truncateCircularReferences(value, numCycles = 0) { const stack = []; return cloneDeepWith(value, (val, _key, parent) => { // pop any stack elements from other objects while (stack.length && stack.at(-1) !== parent) stack.pop(); // we have reached a circular reference if (stack.includes(val)) { return evaluateCircularReference(val, numCycles); } // add this value to the stack for children if (val && typeof val === 'object') stack.push(val); }); } function evaluateCircularReference(value, depth = 0) { if (depth <= 0) return {}; return cloneDeepWith(value, (val, _key, _obj, stack) => { // we have reached a circular reference if (stack && stack.has(val)) { return evaluateCircularReference(val, depth - 1); } }); }