// 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.
 *
 * @template T The type of the input record.
 *
 * @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";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * 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]),
  );
}

// denoCacheMetadata={"headers":{"set-cookie":"__cf_bm=PoXPTHnYneFN2CcAQgEWqabq50M_q3tkSNOPDsak3J4-1785241874.9563522-1.0.1.1-iyjkVeFEv4FCIOeh5WHlkazfy.PXcKJEpo101ebvWBNTOAIW5pcUu3xTlqngdSZiR7Ug2LZVE9ekWnn3E8yyKrUNudRVaQlG.3cVKylGf8FzJlTXl72mdikr12eZJyb9; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","content-type":"text/typescript","access-control-allow-origin":"*","etag":"\"e010343403a756d5adcae29172078efa\"","vary":"Origin","x-content-type-options":"nosniff","cf-ray":"a223e6564f067db6-LAX","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","x-jsr-backend":"modules","date":"Tue, 28 Jul 2026 12:31:15 GMT","access-control-expose-headers":"*","alt-svc":"h3=\":443\"; ma=86400","cache-control":"public, max-age=31536000, immutable","cross-origin-resource-policy":"cross-origin","x-robots-tag":"noindex","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","content-length":"1204","server":"cloudflare","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=6T49paye44uwgkaW8fVJLBUxGXJ285HBuSrKGfWM8GaMLtNGMBh7Co1ap39dxfH%2BO4lpDYfvw9lC4c8%2BJZKEbGeL62%2BdbzphtWv7GyrCAgL%2FSB69L4yKQ%2Bs%3D\"}]}"},"url":"https://jsr.io/@std/collections/0.224.2/invert.ts","time":1785241875}