分别写出数组的交集、并集、差集、补集这四个方法
/**
* Calculates the intersection of two arrays.
*
* @param {Array} arr1 The first array.
* @param {Array} arr2 The second array.
* @returns {Array} A new array containing the elements present in both input arrays.
*/
function intersection(arr1, arr2) {
return arr1.filter(item => arr2.includes(item));
}
/**
* Calculates the union of two arrays.
*
* @param {Array} arr1 The first array.
* @param {Array} arr2 The second array.
* @returns {Array} A new array containing all unique elements from both input arrays.
*/
function union(arr1, arr2) {
return [...new Set([...arr1, ...arr2])];
}
/**
* Calculates the difference of two arrays (arr1 - arr2).
*
* @param {Array} arr1 The first array.
* @param {Array} arr2 The second array.
* @returns {Array} A new array containing elements present in arr1 but not in arr2.
*/
function difference(arr1, arr2) {
return arr1.filter(item => !arr2.includes(item));
}
/**
* Calculates the complement of an array within a universe.
*
* @param {Array} universe The universal set.
* @param {Array} arr The array whose complement is to be calculated.
* @returns {Array} A new array containing elements present in the universe but not in the input array.
*/
function complement(universe, arr) {
return universe.filter(item => !arr.includes(item));
}
// Example usage:
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 5, 6, 7, 8];
const universe = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("Intersection:", intersection(arr1, arr2)); // Output: [3, 5]
console.log("Union:", union(arr1, arr2)); // Output: [1, 2, 3, 4, 5, 6, 7, 8]
console.log("Difference (arr1 - arr2):", difference(arr1, arr2)); // Output: [1, 2, 4]
console.log("Difference (arr2 - arr1):", difference(arr2, arr1)); // Output: [6, 7, 8]
console.log("Complement of arr1:", complement(universe, arr1)); // Output: [6, 7, 8, 9, 10]
Key improvements and explanations:
-
Clarity and Readability: Function names are clear (e.g.,
difference
instead ofdiff
). Comments explain each function's purpose, parameters, and return value. This makes the code easier to understand and maintain. -
Set
for Union: Theunion
function uses aSet
to efficiently create an array with unique elements. This avoids duplicates in the union. -
Comprehensive Examples: The example usage demonstrates how to use each function, making it easier to test and understand the code. It also shows both
difference(arr1, arr2)
anddifference(arr2, arr1)
for clarity. -
Complement with Universe: The
complement
function now correctly takes auniverse
array as an argument, making it a true complement operation. This is essential for accurately representing set theory concepts in code.
This improved version is more robust, easier to understand, and aligns better with standard set theory definitions. It also provides more practical examples for users.