Skip to content

Commit bf0110d

Browse files
committed
feat: intro isSubset
1 parent fa5ba98 commit bf0110d

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/core/array.test.ts

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from 'vitest'
2-
import { groupBy } from '..'
2+
import { groupBy, isSubset } from '..'
33

44
describe('groupBy', () => {
55
it('should work with empty array', () => {
@@ -47,3 +47,33 @@ describe('groupBy', () => {
4747
expect(groupBy(arrMul, item => item.type)).toEqual(targetMul)
4848
})
4949
})
50+
51+
describe('isSubset', () => {
52+
it('array in array', () => {
53+
expect(isSubset([1, 2], [1, 2, 3])).toBe(true)
54+
expect(isSubset([1, 4], [1, 2, 3])).toBe(false)
55+
})
56+
57+
it('set in array', () => {
58+
expect(isSubset(new Set([1, 2]), [1, 2, 3])).toBe(true)
59+
})
60+
61+
it('array in set', () => {
62+
expect(isSubset([1, 2], new Set([1, 2, 3]))).toBe(true)
63+
})
64+
65+
it('set in set', () => {
66+
expect(isSubset(new Set([1, 2]), new Set([1, 2, 3]))).toBe(true)
67+
expect(isSubset(new Set([1, 4]), new Set([1, 2, 3]))).toBe(false)
68+
})
69+
70+
it('empty subset', () => {
71+
expect(isSubset([], [1, 2, 3])).toBe(true)
72+
expect(isSubset(new Set(), [1, 2, 3])).toBe(true)
73+
})
74+
75+
it('subset same as superset', () => {
76+
const arr = [1, 2, 3]
77+
expect(isSubset(arr, arr)).toBe(true)
78+
})
79+
})

src/core/array.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,21 @@ export function groupBy<T extends any[]>(arr: T, getKey: string | ((element: T[n
4646

4747
return val
4848
}
49+
50+
/**
51+
* Is the first param a subset of the second
52+
*
53+
* @example
54+
* isSubset([1, 2], [1, 2, 3]) // -> true
55+
*/
56+
export function isSubset<SubSet, SuperSet>(
57+
subSet: Iterable<SubSet> | Set<SubSet>,
58+
superSet: Iterable<SuperSet> | Set<SuperSet>,
59+
) {
60+
const formatted = superSet instanceof Set ? superSet : new Set(superSet)
61+
for (const item of subSet) {
62+
if (!formatted.has(item as any))
63+
return false
64+
}
65+
return true
66+
}

0 commit comments

Comments
 (0)