enter image description hereI have been trying to solve DSA problems using JS. So the issue I faced initially was taking user input. So went and searched and got that I can use readline module to do the same. So created an Interface and tried getting user Input, but it seem to be stuck after taking the user Input. Unable to figure out whats wrong, not getting any error as well.

/* Given an array and Q queries, where a query looks like the following,
(l,r)--> l,r are the indices of the array. For each query, you need to find the sum between the given indices
*/
import { getUserInput } from "../index.js";

async function preCompute() {
  let arraySize = 0;
  // get the number for user inputs
  arraySize = await getUserInput("Enter the array size : ");
  console.log("ARRAY SIZE", arraySize);
  const userInputs = [];
  for (let i = 0; i < Number(arraySize.trim()); i++) {
    const currentUserInput = await getUserInput("Enter the number");
    userInputs.push(Number(currentUserInput.trim()));
  }
  const prefixSumArray = [];
  for (let i = 0; i < arraySize; i++) {
    if (i === 0) {
      prefixSumArray[i] = userInputs[i];
    } else {
      prefixSumArray[i] = prefixSumArray[i - 1] + userInputs[i];
    }
  }
  let Q = 0;
  Q = await getUserInput("Enter the number of queries i.e Q");
  for (let i = 0; i < Q; i++) {
    const queryInput = await getUserInput(
      "Enter space separated value for l and r"
    );
    const [l, r] = queryInput.split(" ");
    console.log(
      `Sum between l and r: ${
        l !== 0 ? prefixSumArray[r] - prefixSumArray[l - 1] : prefixSumArray[r]
      }`
    );
  }
}

preCompute();

我的index.js如下所示:

import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

const rl = readline.createInterface({
  input,
  output,
});

export const getUserInput = (prompt) => {
  return new Promise((resolve) => {
    rl.question(prompt, (answer) => {
      console.log("Running callback to resolve");
      resolve(answer);
    });
  });
};

如果有人能指出问题所在,那就太好了.

推荐答案

您使用的是readlinepromiseAPI,因此不应将回调参数传递给rl.question.该方法返回promise .因此,您的getUserInput可能是这样的:

export const getUserInput = (prompt) => rl.question(prompt);

其次,一旦完成,就应该关闭与I/O流的接口.这可以作为preCompute年后的最后声明:

rl.close();

Javascript相关问答推荐

设置默认值后动态更新japbox或调色板

foreach循环中的Typescript字符串索引

深嵌套的ng-container元素仍然可以在Angular 布局组件中正确渲染内容吗?

yarn安装一个本地npm包,以便本地包使用main项目的node_modules(ckeditor-duplicated-modules错误)

Phaser 3 console. log()特定游戏角色的瓷砖属性

如何粗体匹配的字母时输入搜索框使用javascript?

配置WebAssembly/Emscripten本地生成问题

在带有背景图像和圆形的div中添加长方体阴影时的重影线

为什么Mutations 观察器用微任务队列而不是macrotask队列处理?

如何将Cookie从服务器发送到用户浏览器

是什么导致了这种奇怪的水平间距错误(?)当通过JavaScript将列表项元素追加到无序列表时,是否在按钮之间?

使用带有HostBinding的Angular 信号来更新样式?

未捕获的运行时错误:调度程序为空

如何访问此数组中的值?

使用RxJS from Event和@ViewChild vs KeyUp事件和RxJS主题更改输入字段值

postman 预请求中的hmac/sha256内标识-从js示例转换

Pevent触发material 用户界面数据网格中的自动保存

是否有静态版本的`instanceof`?

使用props 将VUE 3组件导入JS文件

使用Java脚本替换字符串中的小文本格式hashtag