UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 1.22 kB
{"version":3,"file":"invert-CcmATa3k.cjs","names":[],"sources":["../src/functions/invert/invert.ts"],"sourcesContent":["import type { Writable } from 'type-fest';\n\n/**\n * Inverts the keys and values of an object.\n * @param object The object to invert.\n * @returns A new object with the keys and values inverted.\n *\n * If the object has duplicate values, the last key will be used.\n * @example\n * ```typescript\n * invert({\n * a: 'x',\n * b: 'y',\n * c: 'z'\n * }); // { x: 'a', y: 'b', z: 'c' }\n * ```\n */\nexport function invert<\n /* const generic is used to make sure we capture the value as a string literal */ const T extends\n Record<PropertyKey, PropertyKey>,\n>(\n object: T\n): // we run it through writeable to simplify the type and \"remove\" the effect of the const generic parameter.\nWritable<Inverted<T>> {\n return Object.fromEntries(\n Object.entries(object).map(([key, value]) => [value, key])\n ) as Writable<Inverted<T>>;\n}\n\ntype Inverted<T extends Record<PropertyKey, PropertyKey>> = {\n [K in keyof T as T[K]]: K;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,SAAgB,OAId,QAEoB;AACpB,QAAO,OAAO,YACZ,OAAO,QAAQ,OAAO,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,OAAO,IAAI,CAAC,CAC3D"}