@modern-kit/utils
Version:
1 lines • 2.4 kB
Source Map (JSON)
{"version":3,"file":"index.cjs","sources":["../../../src/array/countBy/index.ts"],"sourcesContent":["import { identity } from '../../common/identity';\n\n/**\n * @description 배열의 각 요소가 몇 번 등장하는지 세어 객체로 반환하는 함수입니다.\n *\n * @template T - 배열의 타입\n * @param {T} arr - 배열\n * @returns {Record<T[number], number>} 배열의 각 요소의 개수를 담은 객체\n *\n * @example\n * countBy([1, 2, 3, 2, 1]);\n * // { 1: 2, 2: 2, 3: 1 }\n */\nexport function countBy<T extends readonly any[]>(\n arr: T\n): Record<T[number], number>;\n\n/**\n * @description 배열의 각 요소가 몇 번 등장하는지 세어 객체로 반환하는 함수입니다.\n *\n * iteratee를 전달하면 각 요소를 iteratee에 전달하여 반환된 값을 기준으로 몇 번 등장하는지 세어 객체로 반환합니다.\n *\n * @template T - 배열의 타입\n * @template K - iteratee의 반환 타입\n * @param {T} arr - 배열\n * @param {K} iteratee - 각 요소를 변환하는 함수\n * @returns {Record<K, number>} 배열의 각 요소의 개수를 담은 객체\n *\n * @example\n * countBy([1, 2, 3], (value) => value.toString());\n * // { '1': 1, '2': 1, '3': 1 }\n *\n * countBy([{ address: 'seoul' }, { address: 'incheon' }, { address: 'seoul' }], (value) => value.address);\n * // { seoul: 2, incheon: 1 }\n */\nexport function countBy<T extends readonly any[], K extends PropertyKey>(\n arr: T,\n iteratee: (value: T[number]) => K\n): Record<K, number>;\n\nexport function countBy<T extends readonly any[], K extends PropertyKey>(\n arr: T,\n iteratee?: (value: T[number]) => K\n): Record<K, number> {\n const iterateeToUse = iteratee ?? identity;\n const result = {} as Record<K, number>;\n\n for (let i = 0; i < arr.length; i++) {\n const value = arr[i] as T[number];\n const key = iterateeToUse(value) as K;\n\n result[key] = (result[key] || 0) + 1;\n }\n\n return result;\n}\n"],"names":["identity"],"mappings":";;;;AAwCO,SAAS,OAAA,CACd,KACA,QAAA,EACmB;AACnB,EAAA,MAAM,gBAAgB,QAAA,IAAYA,uBAAA;AAClC,EAAA,MAAM,SAAS,EAAC;AAEhB,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,CAAI,QAAQ,CAAA,EAAA,EAAK;AACnC,IAAA,MAAM,KAAA,GAAQ,IAAI,CAAC,CAAA;AACnB,IAAA,MAAM,GAAA,GAAM,cAAc,KAAK,CAAA;AAE/B,IAAA,MAAA,CAAO,GAAG,CAAA,GAAA,CAAK,MAAA,CAAO,GAAG,KAAK,CAAA,IAAK,CAAA;AAAA,EACrC;AAEA,EAAA,OAAO,MAAA;AACT;;;;"}