@@ -382,8 +382,10 @@ export function inRange(value: number, min: number, max: number): boolean {
382382 * Splits an array into chunks of a fixed size.
383383 *
384384 * @example
385+ * ```ts
385386 * chunk([1,2,3,4,5,6,7], 3); // [[1,2,3],[4,5,6],[7]]
386387 * chunk(['a','b','c','d'], 2); // [['a','b'], ['c','d']]
388+ * ```
387389 */
388390export function chunk < T > ( arr : T [ ] , size : number ) : T [ ] [ ] {
389391 if ( size <= 0 ) throw new Error ( "chunk size must be > 0" ) ;
@@ -394,3 +396,53 @@ export function chunk<T>(arr: T[], size: number): T[][] {
394396 }
395397 return result ;
396398}
399+
400+ /**
401+ * Returns the union of multiple arrays.
402+ *
403+ * @example
404+ * ```ts
405+ * union([1,2,3], [2,3,4]); // [1,2,3,4]
406+ * union(['a','b','c'], ['b','c','d']); // ['a','b','c','d']
407+ * ```
408+ */
409+ export function union < T > ( ...lists : T [ ] [ ] ) : T [ ] {
410+ return [ ...new Set ( lists . flat ( ) ) ] ;
411+ }
412+
413+ /**
414+ * Returns the difference of multiple arrays.
415+ *
416+ * @example
417+ * ```ts
418+ * difference([1,2,3], [2,3,4]); // [1]
419+ * difference(['a','b','c'], ['b','c','d']); // ['a']
420+ * ```
421+ */
422+ export function difference < T > ( ...lists : T [ ] [ ] ) : T [ ] {
423+ const set = new Set ( lists [ 0 ] ) ;
424+ for ( const list of lists . slice ( 1 ) ) {
425+ for ( const item of list ) {
426+ set . delete ( item ) ;
427+ }
428+ }
429+ return Array . from ( set ) ;
430+ }
431+
432+ /**
433+ * Returns the intersection of multiple arrays.
434+ *
435+ * @example
436+ * ```ts
437+ * intersection([1,2,3], [2,3,4]); // [2,3]
438+ * intersection(['a','b','c'], ['b','c','d']); // ['b','c']
439+ * ```
440+ */
441+ export function intersection < T > ( ...lists : T [ ] [ ] ) : T [ ] {
442+ if ( lists . length === 0 ) return [ ] ;
443+
444+ return lists . reduce ( ( acc , current ) => {
445+ const currentSet = new Set ( current ) ;
446+ return acc . filter ( ( item ) => currentSet . has ( item ) ) ;
447+ } ) ;
448+ }
0 commit comments