Skip to content

Commit

Permalink
feat(intersects): let identity callback return any value (#11)
Browse files Browse the repository at this point in the history
* feat(intersects): let `identity` return any value

* test: intersects with objects and no identity function
  • Loading branch information
aleclarson authored Jun 25, 2024
1 parent 6a29825 commit 49a0dc4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/array/intersects.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
/**
* Given two arrays, returns true if any elements intersect
*/
export const intersects = <T, K extends string | number | symbol>(
export const intersects = <T, K>(
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<string | number | symbol, boolean>)
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))
}
11 changes: 11 additions & 0 deletions src/array/tests/intersects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
})

0 comments on commit 49a0dc4

Please sign in to comment.