Closed 981377660LMT closed 2 years ago
例如 make 函数,快速初始化数组并根据参数推断返回的数组维度
type MakeArray< Length extends string, Result extends any[] = [] > = `${Result['length']}` extends Length ? Result : MakeArray<Length, [...Result, 1]> type PopLength<T extends any[]> = T extends [...infer F, number] ? [...F]['length'] : 0 type MinusOne<N extends number> = PopLength<MakeArray<`${N}`>> type NestedArray<ArrayItem = any, Depth extends number = 1> = Depth extends 1 ? ArrayItem[] : NestedArray<ArrayItem[], MinusOne<Depth>> /** * * @param initValue 数组初始化值 * @param sizes 数组各个维度的大小 * @returns */ function make<T = number, S extends number[] = []>( initValue: T, ...size: S ): NestedArray<T, S['length']> { const dimension = size.length if (dimension === 1) return Array(size[0]).fill(initValue) as any return Array.from({ length: size.shift()! }, () => make(initValue, ...size)) as any } if (require.main === module) { console.log(make(2, 10)) console.log(make(2, 2, 3)) console.log(make(0, 2, 3, 4)) // [ // 2, 2, 2, 2, 2, // 2, 2, 2, 2, 2 // ] // [ [ 2, 2, 2 ], [ 2, 2, 2 ] ] // [ // [ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ], // [ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ] // ] }
还有一些好的想法,不知道是否支持PR,谢谢!
欢迎所有类型的 Issue 和 PR!为保持一致性和易用性,contest.js 提供功能的方式和命名主要参考 C++ STL、ES6、Java Builtin。所以建议新的功能最好找到类似的 ES6 特性、STL 函数、Java 函数的设计,使用和它们一样风格的接口、函数签名。
例如 make 函数,快速初始化数组并根据参数推断返回的数组维度
还有一些好的想法,不知道是否支持PR,谢谢!