虽然我不熟悉 Immutable.js,但问题是T
是必须在文档中定义的模板。看,你的函数真正返回的是一个数字列表的列表。所以T
决心List<Number>
你的固定文档将类似于:
/**
* @param {Number} n
* @return {List<List<Number>>}
*/
你可以摆脱*
and 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}]`);
}