UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 2.64 kB
{"version":3,"sources":["../../src/functions/objectEntries/objectEntries.ts","../../src/functions/objectFromEntries/objectFromEntries.ts","../../src/functions/mapKeys/mapKeys.ts"],"names":[],"mappings":";AAEO,IAAM,gBAA8B,OAAO;;;ACF3C,IAAM,oBAAuC,OAAO;;;ACUpD,SAAS,QACd,QACA,gBAKuB;AACvB,SAAO;AAAA,IACL,cAAc,MAAM,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM;AAAA,MAC1C,eAAe,KAAK,OAAO,MAAM;AAAA,MACjC;AAAA,IACF,CAAC;AAAA,EACH;AACF","sourcesContent":["import { CastToString, KeysOfUnion } from '../../types';\n\nexport const objectEntries: ObjetEntries = Object.entries;\n\n/**\n * Returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. (The only important difference is that a for...in loop enumerates properties in the prototype chain as well.)\n * Same as `Object.entries()` but returns a typed array.\n * @param object An object whose enumerable own property [key, value] pairs are to be returned.\n * @returns An array of the given object's own enumerable string-keyed property [key, value] pairs.\n */\ntype ObjetEntries = <T extends object>(\n object: T\n) => Array<[CastToString<KeysOfUnion<T>>, T[keyof T]]>;\n","export const objectFromEntries: ObjectFromEntries = Object.fromEntries;\n\n/**\n * Returns a new object from an iterable of key-value pairs.\n * Same as `Object.fromEntries()` but returns a typed object.\n * @param entries An iterable object that contains key-value entries.\n * @returns A new object from the given iterable of key-value pairs.\n * @example\n * ```ts\n * objectFromEntries([\n * ['a', 1],\n * ['b', 2],\n * ['c', 3]\n * ]);\n * // { a: 1, b: 2, c: 3 }\n */\ntype ObjectFromEntries = <K extends PropertyKey, V>(\n entries: Iterable<readonly [K, V]>\n) => Record<K, V>;\n","import { CastToString } from '../../types';\nimport { objectEntries } from '../objectEntries';\nimport { objectFromEntries } from '../objectFromEntries';\n\n/**\n * Returns a new object with the same values as the given object, but with each key mapped to a new key as returned by the given mapper function.\n * @param object The object to map the keys of.\n * @param mapperFunction The function to map the keys with.\n * @returns A new object with the mapped keys.\n */\nexport function mapKeys<T extends object, K extends PropertyKey>(\n object: T,\n mapperFunction: (\n key: CastToString<keyof T>,\n value: T[keyof T],\n object: T\n ) => K\n): Record<K, T[keyof T]> {\n return objectFromEntries(\n objectEntries(object).map(([key, value]) => [\n mapperFunction(key, value, object),\n value,\n ])\n );\n}\n"]}