【问题标题】:How to convert stream into variables in typescript如何将流转换为打字稿中的变量
【发布时间】:2019-12-23 10:41:16
【问题描述】:

有一个输入文件(file.in)。

4  
5   
1 2  
2 4  
3 1  
3 4  
4 2  

在打字稿中,逐行读取输入文件。

const graphsMain = () => {

    let lineReader = require('readline').createInterface({
        input: require('fs').createReadStream('file.in')
    });

    lineReader.on('line', function (line) {
        console.log('Line from file:', line);
    });
}

graphsMain();

在 C++ 中,我可以通过编码来做到这一点。

#include <iostream>

using namespace std;

bool A[10][10];

int main() {
  int x, y, nodes, edges;
  cin >> nodes; // Number of nodes
  cin >> edges; // Number of edges
  for (int i = 0; i < edges; ++i) {
    cin >> x >> y;
    A[x][y] = true; 
  }

  return 0;
}

但是,我不知道如何在 typescript 中实现。请随时发表评论。

【问题讨论】:

    标签: javascript typescript graph-algorithm


    【解决方案1】:

    我认为这里的问题是,如果您是从 C++ 进入 Javascript 世界,那么您编写的代码的实际执行方式会存在很大的概念差异。 C++ 严重依赖同步执行,而 Javascript 世界更侧重于异步执行。

    您尝试解决的具体问题将通过您尝试使用的异步 Node API 以这种方式实现:

    // imports, or require()s as in your code are like conceptually equivalent
    // to #include in C++, hence should be at the beginning of the file, not somewhere
    // in the middle.
    import * as fs from 'fs'
    import * as readline from 'readline'
    
    const graphsMain = () => {
        let lineReader = readline.createInterface({
            input: fs.createReadStream('file.in')
        });
    
        let lineCount = 0;
        let nodes: number | undefined
        let edges: number | undefined
        let buffer: number[][] = []
        lineReader.on('line', function (line) {
            console.log('Line from file:', line);
            if (lineCount == 0) {
              nodes = parseInt(line) 
            } else if (lineCount == 1) {
              edges = parseInt(line)
            } else {
              const coordinates = line.split(' ').map((item) => parseInt(item)) 
              buffer.push(coordinates)
            }
            lineCount++
        });
    
        lineReader.on('close', function () {
            console.log('end. I got these values:', nodes, edges, buffer)   
        });
    }
    
    graphsMain();
    

    也就是说,您可以通过多种不同的方式来解决它,包括您可能更熟悉的同步 API,例如 fs.readFileSync

    虽然我觉得您的 Javascript 之旅才刚刚开始,但我强烈建议您阅读一下整个生态系统依赖于异步代码执行的重点。 Mozilla MDN 有很多文章解释了这一切。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2019-02-08
      • 2016-09-12
      • 2022-07-21
      • 2019-06-05
      • 2021-07-15
      • 2019-01-21
      相关资源
      最近更新 更多