JSDoc with和Immutable.js注释中的数据结构

Mar*_*ory 5 javascript jsdoc immutable.js

我从函数返回Immutable.js List数据结构.

PHPStorm自动附加以下内容 @returns {*|List<T>|List<any>}.

Eslint给我警告"T"类型的未解决变量.我在哪里可以找到Immutable.js注释的文档?

如何描述将在Eslint中传递的List的@returns注释形状?

/**
 * @param n
 * @returns {*|List<T>|List<any>}
 */
const getList = (n) => {
  let list = Immutable.List()

  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      list = list.push(Immutable.List.of(i, j))
    }
  }

  return list
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*iva 5

虽然我不熟悉 Immutable.js,但问题是它T是一个必须在文档中定义的模板。看,你的函数真正返回的是一个数字列表的列表。因此,TList<Number>的固定文档将类似于:

/**
 * @param {Number} n
 * @return {List<List<Number>>}
 */
Run Code Online (Sandbox Code Playgroud)

而且您可以摆脱*andList<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;
}
Run Code Online (Sandbox Code Playgroud)

此外,不仅时间而且内存使用也在成倍增加。根据您使用它的方式,您可能希望将您的函数变成生成器函数,这将“神奇地”使其使用恒定空间,即,无论变得有多大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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为了能够将其用作生成器,您需要按需调用它。例如,如果您将这些数字对打印到某个输出:

for (const pair of getList(4)) {
    console.info(`...and here comes another pair: [${pair}]`);
}
Run Code Online (Sandbox Code Playgroud)