Generic Functions Accept Iterable Inputs

Type one function parameter as Iterable<T> so arrays, Sets, Map views, and generators all flow through the same loop without per-type overloads.

TypescriptData Integrity

Code

typescriptsnippet
27 lines
// Iterable<T> 让函数同时接受数组、Set、Map 视图与生成器
function sum(values: Iterable<number>): number {
  let total = 0;
  for (const value of values) {
    total += value;
  }
  return total;
}

console.log('array:', sum([1, 2, 3]));
console.log('set:', sum(new Set([4, 5])));
console.log('map values:', sum(new Map([['a', 10], ['b', 20]]).values()));

function* countdown(from: number): Generator<number> {
  for (let n = from; n > 0; n--) {
    yield n;
  }
}

console.log('generator:', sum(countdown(4)));

// 泛型 Iterable 消费者:任意可迭代源统一收进字符串
function joinAll(items: Iterable<string>, separator: string): string {
  return [...items].join(separator);
}

console.log('joined:', joinAll(new Set(['deploy', 'verify']), ' -> '));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

array: 6
set: 9
map values: 30
generator: 10
joined: deploy -> verify

How it works

Both consumers are single-for-loop functions: sum folds an Iterable<number> into a total, joinAll spreads its input into [...items].join(separator) — and the demo feeds them an array, a Set, a Map view, and the countdown generator.

for (const value of values) and for (let n = from; n > 0; n--) nest, one inside the other.

The result is a fresh construction, so callers can keep their originals.

Applying it

function sum(values: Iterable<number>) accepts all four input kinds through one parameter type — no per-container overloads anywhere in the file.

The five console.log calls each print one labeled result — array: 6, set: 9, map values: 30, generator: 10, joined: deploy -> verify — so every input kind’s path through sum/joinAll lands on its own line.

Statements that matter

return [...items].join(separator);
total += value;

Interactive Tools for This Topic

FAQ

Does `sum` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `sum`, `joinAll` at load time.