2024-05-12 23:02:00 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
|
|
// This module is browser compatible.
|
|
|
|
|
|
|
|
/** Return type for {@linkcode invert}. */
|
|
|
|
export type InvertResult<T extends Record<PropertyKey, PropertyKey>> = {
|
|
|
|
[P in keyof T as T[P]]: P;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Composes a new record with all keys and values inverted.
|
|
|
|
*
|
|
|
|
* If the record contains duplicate values, subsequent values overwrite property
|
|
|
|
* assignments of previous values. If the record contains values which aren't
|
|
|
|
* {@linkcode PropertyKey}s their string representation is used as the key.
|
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T The type of the input record.
|
2024-05-12 23:02:00 +00:00
|
|
|
*
|
|
|
|
* @param record The record to invert.
|
|
|
|
*
|
|
|
|
* @returns A new record with all keys and values inverted.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
|
|
|
* ```ts
|
|
|
|
* import { invert } from "@std/collections/invert";
|
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";
|
2024-05-12 23:02:00 +00:00
|
|
|
*
|
|
|
|
* const record = { a: "x", b: "y", c: "z" };
|
|
|
|
*
|
|
|
|
* assertEquals(invert(record), { x: "a", y: "b", z: "c" });
|
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function invert<T extends Record<PropertyKey, PropertyKey>>(
|
|
|
|
record: Readonly<T>,
|
|
|
|
): InvertResult<T> {
|
|
|
|
return Object.fromEntries(
|
|
|
|
Object.entries(record).map(([key, value]) => [value, key]),
|
|
|
|
);
|
|
|
|
}
|