"JavaScript hasCircularReference()"의 두 판 사이의 차이

1번째 줄: 1번째 줄:
==개요==
==개요==
;JavaScript hasCircularReference()
;JavaScript hasCircularReference()
<syntaxhighlight lang='javascript' run>
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
</syntaxhighlight>


<syntaxhighlight lang='javascript' run>
<syntaxhighlight lang='javascript' run>

2025년 2월 16일 (일) 14:24 판

개요

JavaScript hasCircularReference()
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
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
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) {
    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
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}