Set Logic

🔹 1. Union (اجتماع)

ترکیب دو مجموعه و حذف مقادیر تکراری.

const a = new Set([1, 2, 3]); const b = new Set([3, 4, 5]); const union = new Set([...a, ...b]); console.log(union); // Set(5) {1, 2, 3, 4, 5}

🔹 2. Intersection (اشتراک)

مقادیر مشترک بین دو مجموعه.

const intersection = new Set([...a].filter(x => b.has(x))); console.log(intersection); // Set(1) {3}

🔹 3. Difference (تفاضل)

عناصری که در مجموعه‌ی A هستند ولی در B نیستند.

const difference = new Set([...a].filter(x => !b.has(x))); console.log(difference); // Set(2) {1, 2}

🔹 4. Symmetric Difference (تفاضل متقارن)

عناصری که فقط در یکی از مجموعه‌ها وجود دارند (نه هر دو).

const symDiff = new Set([...a, ...b].filter(x => !(a.has(x) && b.has(x)))); console.log(symDiff); // Set(4) {1, 2, 4, 5}

🔹 5. Subset (زیرمجموعه)

بررسی می‌کنه که آیا مجموعه A یک زیرمجموعه از B هست یا نه.

const c = new Set([1, 2]); const isSubset = [...c].every(x => a.has(x)); console.log(isSubset); // true (چون c ⊆ a)

🎯 تمرین عملی – همه عملیات‌ها در یکجا

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript Set Logic</title> </head> <body> <h2>JavaScript Set Logic</h2> <pre id="output"></pre> <script> const output = document.getElementById("output"); const A = new Set([1, 2, 3]); const B = new Set([3, 4, 5]); // Union const union = new Set([...A, ...B]); output.innerText += "Union: " + JSON.stringify([...union]) + "\n"; // Intersection const intersection = new Set([...A].filter(x => B.has(x))); output.innerText += "Intersection: " + JSON.stringify([...intersection]) + "\n"; // Difference const difference = new Set([...A].filter(x => !B.has(x))); output.innerText += "Difference (A - B): " + JSON.stringify([...difference]) + "\n"; // Symmetric Difference const symDiff = new Set([...A, ...B].filter(x => !(A.has(x) && B.has(x)))); output.innerText += "Symmetric Difference: " + JSON.stringify([...symDiff]) + "\n"; // Subset const C = new Set([1, 2]); const isSubset = [...C].every(x => A.has(x)); output.innerText += "C subset of A? " + isSubset + "\n"; </script> </body> </html>

📌 نتیجه‌گیری

با استفاده از Set و ترکیب متدهایی مثل has(), filter(), spread operator می‌تونیم منطق مجموعه‌ای رو در جاوااسکریپت پیاده‌سازی کنیم:

  • Union (اجتماع)[...A, ...B]

  • Intersection (اشتراک)filter(x => B.has(x))

  • Difference (تفاضل)filter(x => !B.has(x))

  • Symmetric Difference (تفاضل متقارن) → عناصر غیرمشترک

  • Subset (زیرمجموعه)every(x => A.has(x))