繁体   English   中英

如何在 Typescript 中对未知深度的对象进行递归?

[英]How do I do a recursion over objects of unknown depth in Typescript?

我有一个 JSON 文件,其类别结构的深度未知。 我想确保可以访问所有页面。 我建立了三个嵌套调用,但我认为在这里递归会更好。 不幸的是,我没有 Typescript 关于递归的经验。 有人可以帮我将逻辑放入我可以调用的 function 中吗?

  test.setTimeout(28800000); // 8 hours max.
    // console.log(ofcJSON)
  for (let i = 0; i < ofcJSON.items.length; i++) {
    let currentPage = ofcJSON.items[i].link
    console.log(currentPage)
    if (!currentPage.startsWith("http")) await page.goto(currentPage)
    if (ofcJSON.items[i].items != null) {
        for (let j = 0; j < ofcJSON.items[i].items!.length; j++) {
            let currentPage1 = ofcJSON.items[i].items![j].link
            console.log(currentPage1)
            if (!currentPage1.startsWith("http")) await page.goto(currentPage1)
            if (ofcJSON.items[i].items![j].items != null) {
                for(let k = 0; k < ofcJSON.items[i].items![j].items!.length; k++) {
                    let currentPage2 = ofcJSON.items[i].items![j].items![k].link
                    console.log(currentPage2)
                    if (!currentPage2.startsWith("http")) await page.goto(currentPage2)
                    if (ofcJSON.items![i].items![j].items![k].items != null) {
                        for(let l = 0; l < ofcJSON.items[i].items![j].items![k].items!.length; l++) {
                            let currentPage3 = ofcJSON.items[i].items![j].items![k].items![l].link
                            console.log(currentPage3)
                            if (!currentPage3.startsWith("http")) await page.goto(currentPage3)
                        }
                    }
                }
            }
        }
    }
  }
});

JSON 有 1object,而后者又可以有 1object。 这是可选的。 我不知道深度。

我绘制了一个在typescript 操场上编译和运行的实现,如下所示(单击操场左上角的运行)...

type HttpLink = `http{'s'|''}://${string}`;

function isHttpLink(link: string): link is HttpLink {
  return !!link.match(/^https?:\/\//);
}

type Link = HttpLink | string;

interface Item {
  link: Link;
  items?: Item[];
}

async function goto(link: HttpLink) {
  console.log(`Ran goto on ${link}`);
}

async function visitItemAndDescendants(ancestor: Item) {
  const { link, items } = ancestor;
  if (isHttpLink(link)) {
    await goto(link);
  }
  if (items) {
    for (const item of items) {
      visitItemAndDescendants(item);
    }
  }
}

{
  const exampleItem: Item = {
    link: "https://my.url",
    items: [
      {
        link: "not http",
        items: [
          {
            link:"http://insecure.url"
          },
          {
            link:"https://another.url"
          }
        ],
      },
    ],
  };

  visitItemAndDescendants(exampleItem)
}

感谢您的帮助和同事的帮助,我已经解决了如下问题:

import { Page, test } from '@playwright/test';
import fetch from "node-fetch";

test.use({
    baseURL: "https://www.myUrl.de/"
})

const links: string[] = [];

interface Item {

    link: string;
    items?: Item[];
}

async function getLinks(item: Item): Promise<void> {
    if (item.items && item.items.length > 0) {
        for (let i = 0; i < item.items.length; i++) {
            let currentItem = item.items[i];
            if (currentItem.link && currentItem.link.length > 0) {
                links.push(currentItem.link);
                if (currentItem.items && currentItem.items.length > 0)
                    getLinks(currentItem);
            }
        }
    }
}

test('test', async ({ page }) => {
    test.setTimeout(1560000); // 26 minutes max.

    const ofcJSON = await fetch('https://www.myUrl.de/ofcJSON')
        .then((response) => response.json())
        .then((item) => {
            return item.items
        })

    // console.log(ofcJSON);

    ofcJSON.forEach(element => {
        getLinks(element);
    });

    var maximumNumberOfLinksToCheck = 10;
    var delta = Math.floor(links.length / maximumNumberOfLinksToCheck);

    for (let i = 0; i < links.length; i = i + delta) {
        console.log("Checking page: " + links[i])
        await (page.goto(links[i]));
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM