All files / utils makeConditionalArray.ts

100% Statements 7/7
100% Branches 5/5
100% Functions 4/4
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                                                                3x 20x 6x   20x                       2x   23x  
import { IsNever, Merge } from '../types'
 
export type ConditionalArrayItem<T, K extends keyof T = never> =
  | (IsNever<K> extends true
      ? T
      : Merge<
          T,
          {
            [k in K]: Array<ConditionalArrayItem<T, K>>
          }
        >)
  | false
 
/**
 * 构造条件数组,即允许一个数组的项出现 false 值,且最终 false 值的项目会被排除。
 *
 * @param array 数组
 * @param childrenKey 子数组键
 */
export function makeConditionalArray<T extends any, K extends keyof T>(
  array: Array<ConditionalArrayItem<T, K>>,
  childrenKey: K,
): T[]
/**
 * 构造条件数组,即允许一个数组的项出现 false 值,且最终 false 值的项目会被排除。
 *
 * @param array 数组
 */
export function makeConditionalArray<T extends any>(
  array: Array<ConditionalArrayItem<T>>,
): T[]
export function makeConditionalArray(array: any[], childrenKey?: any): any[] {
  return array.filter(function filter(item) {
    if (item && childrenKey && Array.isArray(item[childrenKey])) {
      item[childrenKey] = (item[childrenKey] as any).filter(filter)
    }
    return !!item
  }) as any
}
 
function makeConditionalArrayFork<T extends any>(): (
  array: Array<ConditionalArrayItem<T>>,
) => T[]
function makeConditionalArrayFork<T extends any, K extends keyof T>(
  childrenKey: K,
): (array: Array<ConditionalArrayItem<T, K>>) => T[]
function makeConditionalArrayFork(childrenKey?: any) {
  // @ts-ignore
  return (array: any) => makeConditionalArray(array, childrenKey)
}
makeConditionalArray.fork = makeConditionalArrayFork