remeda
Version:
A utility library for JavaScript and Typescript.
1 lines • 2.94 kB
Source Map (JSON)
{"version":3,"file":"countBy.cjs","names":["purry"],"sources":["../src/countBy.ts"],"sourcesContent":["import type { BoundedPartial } from \"./internal/types/BoundedPartial\";\nimport { purry } from \"./purry\";\n\n/**\n * Categorize and count elements in an array using a defined callback function.\n * The callback function is applied to each element in the array to determine\n * its category and then counts how many elements fall into each category.\n *\n * @param data - The array.\n * @param categorizationFn - The categorization function.\n * @signature\n * R.countBy(data, categorizationFn)\n * @example\n * R.countBy(\n * [\"a\", \"b\", \"c\", \"B\", \"A\", \"a\"],\n * R.toLowerCase()\n * ); //=> { a: 3, b: 2, c: 1 }\n * @dataFirst\n * @category Array\n */\nexport function countBy<T, K extends PropertyKey>(\n data: ReadonlyArray<T>,\n categorizationFn: (\n value: T,\n index: number,\n data: ReadonlyArray<T>,\n ) => K | undefined,\n): BoundedPartial<Record<K, number>>;\n\n/**\n * Categorize and count elements in an array using a defined callback function.\n * The callback function is applied to each element in the array to determine\n * its category and then counts how many elements fall into each category.\n *\n * @param categorizationFn - The categorization function.\n * @signature\n * R.countBy(categorizationFn)(data)\n * @example\n * R.pipe(\n * [\"a\", \"b\", \"c\", \"B\", \"A\", \"a\"],\n * R.countBy(R.toLowerCase()),\n * ); //=> { a: 3, b: 2, c: 1 }\n * @dataLast\n * @category Array\n */\nexport function countBy<T, K extends PropertyKey>(\n categorizationFn: (\n value: T,\n index: number,\n data: ReadonlyArray<T>,\n ) => K | undefined,\n): (data: ReadonlyArray<T>) => BoundedPartial<Record<K, number>>;\n\nexport function countBy(...args: ReadonlyArray<unknown>): unknown {\n return purry(countByImplementation, args);\n}\n\nconst countByImplementation = <T>(\n data: ReadonlyArray<T>,\n categorizationFn: (\n value: T,\n index: number,\n data: ReadonlyArray<T>,\n ) => PropertyKey | undefined,\n): BoundedPartial<Record<PropertyKey, number>> => {\n const out = new Map<PropertyKey, number>();\n\n for (const [index, item] of data.entries()) {\n const category = categorizationFn(item, index, data);\n if (category !== undefined) {\n const count = out.get(category);\n if (count === undefined) {\n out.set(category, 1);\n } else {\n out.set(category, count + 1);\n }\n }\n }\n\n return Object.fromEntries(out);\n};\n"],"mappings":"wCAqDA,SAAgB,EAAQ,GAAG,EAAuC,CAChE,OAAOA,EAAAA,EAAM,EAAuB,EAAK,CAG3C,MAAM,GACJ,EACA,IAKgD,CAChD,IAAM,EAAM,IAAI,IAEhB,IAAK,GAAM,CAAC,EAAO,KAAS,EAAK,SAAS,CAAE,CAC1C,IAAM,EAAW,EAAiB,EAAM,EAAO,EAAK,CACpD,GAAI,IAAa,IAAA,GAAW,CAC1B,IAAM,EAAQ,EAAI,IAAI,EAAS,CAC3B,IAAU,IAAA,GACZ,EAAI,IAAI,EAAU,EAAE,CAEpB,EAAI,IAAI,EAAU,EAAQ,EAAE,EAKlC,OAAO,OAAO,YAAY,EAAI"}