JavaScript hasCircularReference()

Jmnote (토론 | 기여)님의 2025년 2월 16일 (일) 14:50 판
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요[ | ]

JavaScript hasCircularReference()
function hasCircularReference(obj) {
    const seen = new WeakSet();
    const detect = obj => {
        if (obj && typeof obj === 'object') {
            if (seen.has(obj)) return true;
            seen.add(obj);
            return Object.values(obj).some(detect);
        }
        return false;
    }
    return detect(obj);
}

// 테스트 코드
const a = { x: 1, y: 2 };
const b = { x: 1, y: 2 };
b.z = b; // 순환참조 생성

console.log(hasCircularReference(a)); // false
console.log(hasCircularReference(b)); // true
function hasCircularReference(obj, seen = new WeakSet()) {
    if (obj && typeof obj === 'object') {
        if (seen.has(obj)) return true;
        seen.add(obj);
        for (let key in obj) {
            if (hasCircularReference(obj[key], seen)) return true;
        }
    }
    return false;
}

// 테스트 코드
const a = { x: 1, y: 2 };
const b = { x: 1, y: 2 };
b.z = b; // 순환참조 생성

console.log(hasCircularReference(a)); // false
console.log(hasCircularReference(b)); // true


function hasCircularReference(obj, seen = new WeakSet()) {
    if (obj && typeof obj === 'object') {
        if (seen.has(obj)) return true;
        seen.add(obj);
        return Object.values(obj).some(value => hasCircularReference(value, seen));
    }
    return false;
}

// 테스트 코드
const a = { x: 1, y: 2 };
const b = { x: 1, y: 2 };
b.z = b; // 순환참조 생성

console.log(hasCircularReference(a)); // false
console.log(hasCircularReference(b)); // true
function hasCircularReference(obj, seen = new WeakSet()) {
    return obj && typeof obj === 'object' && (seen.has(obj) || (seen.add(obj), Object.values(obj).some(value => hasCircularReference(value, seen))));
}

// 테스트 코드
const a = { x: 1, y: 2 };
const b = { x: 1, y: 2 };
b.z = b; // 순환참조 생성

console.log(hasCircularReference(a)); // false
console.log(hasCircularReference(b)); // true
const hasCircularReference = (o, s = new WeakSet()) => !!o && typeof o === 'object' && (s.has(o) || (s.add(o), Object.values(o).some(v => hasCircularReference(v, s))));

// 테스트 코드
const a = { x: 1, y: 2 };
const b = { x: 1, y: 2 };
b.z = b; // 순환참조 생성

console.log(hasCircularReference(a)); // false
console.log(hasCircularReference(b)); // true

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}