Skip to content

@utilslib/core/forEach

forEach

函数签名

typescript
function forEach<T>(collection: T[], iteratee: ArrayIteratee<T>): T[]

类型参数

参数名约束默认值描述
T---

参数

参数名类型可选默认值描述
collectionT\[\]--
iterateeArrayIteratee<T>--

返回值

T\[\]

点击查看源码
js
/**
 * 通用的条目迭代器
 * - Map: [key, value]
 * - Set: [value, value]
 * - Array/Iterable: [index, value]
 * - Object: [key, value]
 */
function* entries(data) {
  if (data instanceof Map) yield* data;
  else if (data instanceof Set) {
    for (const v of data) yield [v, v];
  } else if (typeof data[Symbol.iterator] === "function") {
    let i = 0;
    for (const v of data) yield [i++, v];
  } else if (data) {
    yield* Object.entries(data);
  }
}
export function forEach(collection, iteratee) {
  if (collection == null) return collection;
  for (const [key, value] of entries(collection)) {
    if (iteratee(value, key, collection) === false) break;
  }
  return collection;
}
ts
type ArrayIteratee<T> = (
  value: T,
  index: number,
  collection: T[],
) => boolean | void;

type MapIteratee<K, V> = (
  value: V,
  key: K,
  collection: Map<K, V>,
) => boolean | void;

type SetIteratee<T> = (
  value: T,
  value2: T,
  collection: Set<T>,
) => boolean | void;

type ObjectIteratee<T> = (
  value: T,
  key: string,
  collection: Record<string, T>,
) => boolean | void;

/**
 * 通用的条目迭代器
 * - Map: [key, value]
 * - Set: [value, value]
 * - Array/Iterable: [index, value]
 * - Object: [key, value]
 */
function* entries<T, K, V>(
  data: Map<K, V> | Set<T> | Iterable<T> | Record<string, any>,
): Generator<[K | number | string | T, V | T], void, unknown> {
  if (data instanceof Map) yield* data;
  else if (data instanceof Set) {
    for (const v of data) yield [v, v] as [T, T];
  } else if (typeof (data as Iterable<T>)[Symbol.iterator] === "function") {
    let i = 0;
    for (const v of data as Iterable<T>) yield [i++, v] as [number, T];
  } else if (data) {
    yield* Object.entries(data) as [string, any][];
  }
}

export function forEach<T>(collection: T[], iteratee: ArrayIteratee<T>): T[];

export function forEach<K, V>(
  collection: Map<K, V>,
  iteratee: MapIteratee<K, V>,
): Map<K, V>;

export function forEach<T>(
  collection: Set<T>,
  iteratee: SetIteratee<T>,
): Set<T>;

export function forEach<T>(
  collection: Record<string, T>,
  iteratee: ObjectIteratee<T>,
): Record<string, T>;

export function forEach(
  collection: null | undefined,
  iteratee: any,
): null | undefined;

export function forEach(collection: any, iteratee: any): any {
  if (collection == null) return collection;
  for (const [key, value] of entries(collection)) {
    if (iteratee(value, key, collection) === false) break;
  }
  return collection;
}

如有错误,请提交issue :::