Skip to content

Commit

Permalink
intersection (#5)
Browse files Browse the repository at this point in the history
* intersection
* intersectionBy
  • Loading branch information
buzuosheng committed Jul 22, 2023
1 parent b9636da commit 011c3c8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,4 @@ export * from './compose'
export * from './difference'
export * from './async'
export * from './nth'
export * from './intersection'
14 changes: 14 additions & 0 deletions src/intersection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
type by<T> = (item: T) => number | string

export function intersection<T>(...args: Array<T[] | by<T>>): T[] {
if (!args || !args.length) return []
if (args.slice(0, args.length - 1).find(item => typeof item === 'function')) return []
const list: T[][] = args.filter(Array.isArray)
const by: by<T> = typeof args[args.length - 1] === 'function' ? args[args.length - 1] as by<T> : (x => x as number);
return list?.reduce((a, b) => {
const setB = new Set(b.map(by));
return a.filter(c => setB.has(by(c)));
});
}

export { intersection as intersectionBy }
21 changes: 21 additions & 0 deletions test/intersection.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { intersection } from '../src'
import { intersectionBy } from '../src'

describe('should work', function () {
let list = [['a', 'b', 'c'], ['a', 'c'], ['a'], ['a', 'd']]
it('should work', function () {
expect(intersection()).toEqual([])
expect(intersection([])).toEqual([])
expect(intersection([2, 1], [4, 2], [1, 2])).toEqual([2])
expect(intersection([2, 1])).toEqual([2, 1])
expect(intersection(...list)).toEqual(['a'])
})

it('should work with by', function () {
expect(intersectionBy()).toEqual([])
expect(intersectionBy([])).toEqual([])
expect(intersectionBy([{ 'x': 1 }])).toEqual([{ 'x': 1 }])
expect(intersectionBy([2, 1], [4, 2], [1, 2], Math.floor)).toEqual([2])
expect(intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], x => x.x)).toEqual([{ 'x': 1 }])
})
})

1 comment on commit 011c3c8

@vercel
Copy link

@vercel vercel bot commented on 011c3c8 Jul 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.