diff --git a/src/array/intersects.ts b/src/array/intersects.ts index 39cc27ea..b8dd52e3 100644 --- a/src/array/intersects.ts +++ b/src/array/intersects.ts @@ -1,16 +1,15 @@ /** * Given two arrays, returns true if any elements intersect */ -export const intersects = ( +export const intersects = ( listA: readonly T[], listB: readonly T[], identity?: (t: T) => K ): boolean => { if (!listA || !listB) return false - const ident = identity ?? ((x: T) => x as unknown as K) - const dictB = listB.reduce((acc, item) => { - acc[ident(item)] = true - return acc - }, {} as Record) - return listA.some(value => dictB[ident(value)]) + if (identity) { + const known = new Set(listA.map(identity)) + return listB.some(item => known.has(identity(item))) + } + return listB.some(item => listA.includes(item)) } diff --git a/src/array/tests/intersects.test.ts b/src/array/tests/intersects.test.ts index 0a85f717..e37db8ae 100644 --- a/src/array/tests/intersects.test.ts +++ b/src/array/tests/intersects.test.ts @@ -25,4 +25,15 @@ describe('intersects function', () => { expect(_.intersects(cast(null), [])).toBeFalsy() expect(_.intersects([], cast(null))).toBeFalsy() }) + test('works with objects without an identity function', () => { + const obj1 = { id: 1 } + const obj2 = { id: 2 } + const obj3 = { id: 3 } + + let result = _.intersects([obj1, obj2], [obj2, obj3]) + expect(result).toBeTruthy() + + result = _.intersects([obj1], [obj3]) + expect(result).toBeFalsy() + }) })