import { test } from 'node:test'; import assert from 'node:assert/strict'; import { PEOPLE, countBy, emptyReduceWithoutInitial, flattenBuiltin, flattenDeep, flattenReduce, groupBy, namesByLang, run, sum, } from './main.js'; test('sum 用 0 作为初始值,空数组返回 0', () => { assert.equal(sum([1, 2, 3, 4]), 10); assert.equal(sum([]), 0); }); test('空数组 reduce 且无初始值会抛 TypeError', () => { assert.equal(emptyReduceWithoutInitial(), 'TypeError'); }); test('groupBy 按语言分组', () => { const grouped = groupBy(PEOPLE, (p) => p.lang); assert.deepEqual(Object.keys(grouped), ['js', 'go', 'rust']); assert.equal(grouped.js.length, 2); assert.deepEqual(namesByLang(), { js: ['Ada', 'Cara'], go: ['Bob', 'Eve'], rust: ['Dan'], }); }); test('countBy 统计每个键的数量', () => { assert.deepEqual(countBy(PEOPLE, (p) => p.lang), { js: 2, go: 2, rust: 1 }); }); test('reduce 展平与 flat 结果一致(一层)', () => { assert.deepEqual(flattenReduce([[1, 2], [3], [4, 5]]), [1, 2, 3, 4, 5]); assert.deepEqual(flattenBuiltin([[1, 2], [3], [[4, 5]]]), [1, 2, 3, [4, 5]]); }); test('flat(Infinity) 展平所有层级', () => { assert.deepEqual(flattenDeep(), [1, 2, 3, 4]); }); test('run 输出 8 行场景与两条说明', () => { const out = []; const rows = run((s) => out.push(s)); assert.equal(rows.length, 8); assert.equal(out.length, 11); assert.equal(out[4], 'groupBy(lang) => {"js":["Ada","Cara"],"go":["Bob","Eve"],"rust":["Dan"]}'); });