2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2021-09-18 18:29:29 +00:00
|
|
|
// This module is browser compatible.
|
2021-07-15 21:37:53 +00:00
|
|
|
|
|
|
|
/**
|
2023-12-05 08:53:55 +00:00
|
|
|
* Returns all distinct elements that appear in any of the given arrays.
|
2021-07-15 21:37:53 +00:00
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T The type of the array elements.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @param arrays The arrays to get the union of.
|
|
|
|
*
|
|
|
|
* @returns A new array containing all distinct elements from the given arrays.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
2021-07-30 14:49:46 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { union } from "@std/collections/union";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2021-07-30 14:49:46 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* const soupIngredients = ["Pepper", "Carrots", "Leek"];
|
|
|
|
* const saladIngredients = ["Carrots", "Radicchio", "Pepper"];
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* const shoppingList = union(soupIngredients, saladIngredients);
|
2021-07-15 21:37:53 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* assertEquals(shoppingList, ["Pepper", "Carrots", "Leek", "Radicchio"]);
|
2021-07-15 21:37:53 +00:00
|
|
|
* ```
|
|
|
|
*/
|
2023-05-30 23:48:21 +00:00
|
|
|
export function union<T>(...arrays: Iterable<T>[]): T[] {
|
2021-07-15 21:37:53 +00:00
|
|
|
const set = new Set<T>();
|
|
|
|
|
|
|
|
for (const array of arrays) {
|
|
|
|
for (const element of array) {
|
|
|
|
set.add(element);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return Array.from(set);
|
|
|
|
}
|