I 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);
});
});
};
如果有人能指出问题所在,那就太好了.