虽然我对 Immutable.js 不熟悉,但问题是 T 是必须在文档中定义的模板。看,你的函数真正返回的是一个数字列表列表。所以T 解析为List<Number>,您的固定文档将类似于:
/**
* @param {Number} n
* @return {List<List<Number>>}
*/
你可以去掉 * 和 List<any> 作为可能的返回类型,因为你的函数显然总是返回一个数字列表。
就是这样。
关于算法复杂度
附带说明,请记住您编写了一个函数,其处理时间随参数n 呈二次方增长。如果您发现自己经常调用传递相同值的函数,请考虑记住它的返回值:
const memoizedLists = new Map();
/**
* @param {Number} n
* @return {List<List<Number>>}
*/
function getList(n) {
// try to find a previous run for this same value
let result = memoizedLists.get(n);
if (!result) {
// compute it otherwise
result = Immutable.List();
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
result.push(Immutable.List.of(i, j));
}
}
// memoize it for a future invocation
memoizedLists.set(n, result);
}
return result;
}
此外,不仅时间而且内存使用量也呈二次方增长。根据您使用它的方式,您可能希望将您的函数改为生成器函数,这将“神奇地”使其使用恒定空间,即,无论 n 有多大,您的函数将继续使用只是相同数量的内存。这是你的函数变成了生成器函数:
/**
* @generator
* @param {Number} n
* @yields {List<Number>}
*/
function *getList(n) {
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
yield Immutable.List.of(i, j);
}
}
}
为了能够将其用作生成器,您需要按需调用它。例如,如果您将这些数字对打印到某个输出:
for (const pair of getList(4)) {
console.info(`...and here comes another pair: [${pair}]`);
}