All files / utils sampleBy.ts

87.5% Statements 7/8
75% Branches 3/4
100% Functions 2/2
85.71% Lines 6/7

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                                  9x 5x 4x 4x 4x 4x        
import { forOwn, isArray, isObject, sample } from 'lodash-uni'
 
/**
 * 从集合中随机获得一个元素的迭代值。
 *
 * @param collection 集合
 * @param iteratee 迭代函数
 */
export function sampleBy<T, X>(
  collection: T[],
  iteratee: (element: T, index: number) => X,
): X | undefined
export function sampleBy<T extends Record<any, any>, X>(
  collection: T,
  iteratee: <K extends keyof T>(value: T[K], key: K) => X,
): X | undefined
export function sampleBy(collection: any, iteratee: any): any {
  if (isArray(collection)) {
    return sample(collection.map(iteratee))
  } else if (isObject(collection)) {
    const values: any[] = []
    forOwn(collection, (v, k) => values.push(iteratee(v, k)))
    return sample(values)
  }
  return undefined
}