@utilslib/core/isNonEmptyIntersection
(A∩B) 判断两个数组是否存在交集
isNonEmptyIntersection
函数签名
typescript
function isNonEmptyIntersection(...args: Parameters<typeof getArrayIntersection>): boolean描述
(A∩B) 判断两个数组是否存在交集
参数
| 参数名 | 类型 | 可选 | 默认值 | 描述 |
|---|---|---|---|---|
args | Parameters<typeof getArrayIntersection> | 是 | - | - |
返回值
boolean
点击查看源码
js
/**
* (A∩B) 交集
*
* @type {<T, K extends keyof T>(A: T[], B: T[], key: K) => T[]}
* @param {T[]} A - 第一个数组。「主数组,当返回的内容从主数组中获取」
* @param {T[]} B - 第二个数组。
* @param {K extends keyof T} [key] - 可选的字段属性,用于判断交集。
* @returns {T[]} 交集的数组。
*/
function getArrayIntersection(A, B, key) {
if (key) {
const set = new Set(B.map((item) => item[key]));
return A.filter((item) => set.has(item[key]));
}
return A.filter((item) => B.includes(item));
}
/**
* (A∩B) 判断两个数组是否存在交集
*
* @template T - 数组元素类型
* @template K - 用于判断的属性键名类型
* @param {T[]} A - 第一个数组
* @param {T[]} B - 第二个数组
* @param {K} [key] - 可选的用于判断的属性键名
* @returns {boolean} 如果存在交集,则返回 true,否则返回 false。
*/
export function isNonEmptyIntersection(...args) {
const [A, B, key] = args;
return Boolean(getArrayIntersection(A, B, key).length);
}ts
/**
* (A∩B) 交集
*
* @type {<T, K extends keyof T>(A: T[], B: T[], key: K) => T[]}
* @param {T[]} A - 第一个数组。「主数组,当返回的内容从主数组中获取」
* @param {T[]} B - 第二个数组。
* @param {K extends keyof T} [key] - 可选的字段属性,用于判断交集。
* @returns {T[]} 交集的数组。
*/
function getArrayIntersection<T, K extends keyof T = keyof T>(
A: T[],
B: T[],
key?: K,
): T[] {
if (key) {
const set = new Set(B.map((item) => item[key]));
return A.filter((item) => set.has(item[key]));
}
return A.filter((item) => B.includes(item));
}
/**
* (A∩B) 判断两个数组是否存在交集
*
* @template T - 数组元素类型
* @template K - 用于判断的属性键名类型
* @param {T[]} A - 第一个数组
* @param {T[]} B - 第二个数组
* @param {K} [key] - 可选的用于判断的属性键名
* @returns {boolean} 如果存在交集,则返回 true,否则返回 false。
*/
export function isNonEmptyIntersection(
...args: Parameters<typeof getArrayIntersection>
): boolean {
const [A, B, key] = args;
return Boolean(getArrayIntersection(A, B, key).length);
}如有错误,请提交issue :::