UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 1.38 kB
{"version":3,"sources":["../../src/functions/join/join.ts"],"names":[],"mappings":";AASO,SAAS,KACd,UACA,WACoC;AACpC,QAAM,iBAAiB,OAAO,gBAAgB;AAE9C,QAAM,oBACJ,OAAO,cAAc,aAChB,YACD,MAAM;AAEZ,SAAO,SACJ,QAAQ,CAAC,SAAS,OAAO,UAAU;AAAA,IAClC;AAAA,IACA,QAAQ,MAAM,SAAS,IAAI,kBAAkB,KAAK,IAAI;AAAA,EACxD,CAAC,EACA,OAAO,CAAC,SAAS,SAAS,cAAc;AAC7C","sourcesContent":["import { NonFunction } from '../../types/_internal';\n\n/**\n * Same as `Array.prototype.join`, but allows specifying a non-`string` separator.\n * @param elements The elements to join.\n * @param separator The separator to use.\n * @returns An array with the elements joined by the separator.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- only used as generic constraints\nexport function join<T extends NonFunction<any>, U extends NonFunction<any>>(\n elements: ReadonlyArray<NonNullable<T>>,\n separator: U | ((index: number) => U)\n): Array<symbol | U | NonNullable<T>> {\n const emptySeparator = Symbol('emptySeparator');\n\n const separatorFunction =\n typeof separator === 'function'\n ? (separator as (index: number) => NonNullable<U>)\n : () => separator;\n\n return elements\n .flatMap((element, index, array) => [\n element,\n index < array.length - 1 ? separatorFunction(index) : emptySeparator,\n ])\n .filter((item) => item !== emptySeparator);\n}\n"]}