UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 2.31 kB
{"version":3,"file":"difference-DwycZEVK.cjs","names":["createTypeGuard","negate"],"sources":["../src/functions/difference/difference.ts"],"sourcesContent":["import type { IsLiteral } from 'type-fest';\n\nimport { createTypeGuard } from '../createTypeGuard';\nimport { negate } from '../negate';\n\n/**\n * Gets the difference between two arrays.\n * @param array1 The first array.\n * @param array2 The second array.\n * @param comparator A function that determines whether two items are equal.\n * @returns An array with the difference between the two arrays - items that are in the first array but not in the second.\n * @example\n * ```ts\n * difference([1, 2, 3], [2, 3, 4]) // [2, 3]\n * ```\n */\nexport function difference<const T, const S extends T>(\n array1: readonly T[],\n array2: readonly S[],\n comparator?: Comparator<T, S>\n): Array<IsLiteral<T> | IsLiteral<S> extends true ? Exclude<T, S> : T>;\n/**\n * Gets the difference between two arrays.\n * @param array1 The first array.\n * @param array2 The second array.\n * @param comparator A function that determines whether two items are equal.\n * @returns An array with the difference between the two arrays - items that are in the first array but not in the second.\n * @example\n * ```ts\n * difference([1, 2, 3], [2, 3, 4]) // [2, 3]\n * ```\n */\nexport function difference<T, S extends T>(\n array1: readonly T[],\n array2: readonly S[],\n comparator?: Comparator<T, S>\n): Array<IsLiteral<T> | IsLiteral<S> extends true ? Exclude<T, S> : T>;\nexport function difference<T, S extends T>(\n array1: readonly T[],\n array2: readonly S[],\n comparator?: Comparator<T, S>\n): Array<IsLiteral<T> | IsLiteral<S> extends true ? Exclude<T, S> : T> {\n if (!comparator) {\n const isArray2Item = createTypeGuard(array2);\n return array1.filter(negate(isArray2Item)) as Exclude<T, S>[];\n }\n\n return array1.filter(\n (a1): a1 is Exclude<T, S> => !array2.some((a2) => comparator(a1, a2))\n );\n}\n\ntype Comparator<T, S extends T> =\n | ((a: T, b: S) => a is Exclude<T, S>)\n | ((a: T, b: S) => boolean);\n"],"mappings":";;;;AAqCA,SAAgB,WACd,QACA,QACA,YACqE;AACrE,KAAI,CAAC,YAAY;EACf,MAAM,eAAeA,wCAAgB,OAAO;AAC5C,SAAO,OAAO,OAAOC,sBAAO,aAAa,CAAC;;AAG5C,QAAO,OAAO,QACX,OAA4B,CAAC,OAAO,MAAM,OAAO,WAAW,IAAI,GAAG,CAAC,CACtE"}