remeda
Version:
A utility library for JavaScript and Typescript.
1 lines • 2.87 kB
Source Map (JSON)
{"version":3,"file":"indexBy.cjs","names":["purry","out: Partial<Record<K, T>>"],"sources":["../src/indexBy.ts"],"sourcesContent":["import type { BoundedPartial } from \"./internal/types/BoundedPartial\";\nimport { purry } from \"./purry\";\n\n/**\n * Converts a list of objects into an object indexing the objects by the given\n * key.\n *\n * There are several other functions that could be used to build an object from\n * an array:\n * * `fromKeys` - Builds an object from an array of *keys* and a mapper for values.\n * * `pullObject` - Builds an object from an array of items with mappers for *both* keys and values.\n * * `fromEntries` - Builds an object from an array of key-value pairs.\n * Refer to the docs for more details.\n *\n * @param data - The array.\n * @param mapper - The indexing function.\n * @signature\n * R.indexBy(array, fn)\n * @example\n * R.indexBy(['one', 'two', 'three'], x => x.length) // => {3: 'two', 5: 'three'}\n * @dataFirst\n * @category Array\n */\nexport function indexBy<T, K extends PropertyKey>(\n data: ReadonlyArray<T>,\n mapper: (item: T, index: number, data: ReadonlyArray<T>) => K,\n): BoundedPartial<Record<K, T>>;\n\n/**\n * Converts a list of objects into an object indexing the objects by the given\n * key.\n *\n * There are several other functions that could be used to build an object from\n * an array:\n * * `fromKeys` - Builds an object from an array of *keys* and a mapper for values.\n * * `pullObject` - Builds an object from an array of items with mappers for *both* keys and values.\n * * `fromEntries` - Builds an object from an array of key-value pairs.\n * Refer to the docs for more details.\n *\n * @param mapper - The indexing function.\n * @signature\n * R.indexBy(fn)(array)\n * @example\n * R.pipe(\n * ['one', 'two', 'three'],\n * R.indexBy(x => x.length)\n * ) // => {3: 'two', 5: 'three'}\n * @dataLast\n * @category Array\n */\nexport function indexBy<T, K extends PropertyKey>(\n mapper: (item: T, index: number, data: ReadonlyArray<T>) => K,\n): (data: ReadonlyArray<T>) => BoundedPartial<Record<K, T>>;\n\nexport function indexBy(...args: ReadonlyArray<unknown>): unknown {\n return purry(indexByImplementation, args);\n}\n\nfunction indexByImplementation<T, K extends PropertyKey>(\n data: ReadonlyArray<T>,\n mapper: (item: T, index: number, data: ReadonlyArray<T>) => K,\n): BoundedPartial<Record<K, T>> {\n const out: Partial<Record<K, T>> = {};\n\n for (const [index, item] of data.entries()) {\n const key = mapper(item, index, data);\n out[key] = item;\n }\n\n return out as BoundedPartial<Record<K, T>>;\n}\n"],"mappings":"wCAsDA,SAAgB,EAAQ,GAAG,EAAuC,CAChE,OAAOA,EAAAA,EAAM,EAAuB,EAAK,CAG3C,SAAS,EACP,EACA,EAC8B,CAC9B,IAAMC,EAA6B,EAAE,CAErC,IAAK,GAAM,CAAC,EAAO,KAAS,EAAK,SAAS,CAAE,CAC1C,IAAM,EAAM,EAAO,EAAM,EAAO,EAAK,CACrC,EAAI,GAAO,EAGb,OAAO"}