如何将流转换为打字稿中的变量

时间:2019-08-17 11:38:49

标签: javascript typescript graph-algorithm

有一个输入文件(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;
}

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

1 个答案:

答案 0 :(得分: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上有许多文章介绍了所有这些内容。